rename_exchange.c 763 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Program that atomically exchanges two paths using
  4. * the renameat2() system call RENAME_EXCHANGE flag.
  5. *
  6. * Copyright 2022 Red Hat Inc.
  7. * Author: Javier Martinez Canillas <javierm@redhat.com>
  8. */
  9. #define _GNU_SOURCE
  10. #include <fcntl.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. void print_usage(const char *program)
  14. {
  15. printf("Usage: %s [oldpath] [newpath]\n", program);
  16. printf("Atomically exchange oldpath and newpath\n");
  17. }
  18. int main(int argc, char *argv[])
  19. {
  20. int ret;
  21. if (argc != 3) {
  22. print_usage(argv[0]);
  23. exit(EXIT_FAILURE);
  24. }
  25. ret = renameat2(AT_FDCWD, argv[1], AT_FDCWD, argv[2], RENAME_EXCHANGE);
  26. if (ret) {
  27. perror("rename exchange failed");
  28. exit(EXIT_FAILURE);
  29. }
  30. exit(EXIT_SUCCESS);
  31. }