-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexchange.c
78 lines (66 loc) · 1.93 KB
/
exchange.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#define _GNU_SOURCE
#include <fcntl.h>
#include <getopt.h>
#include <gnu/libc-version.h>
#include <linux/fs.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <sys/syscall.h>
#include <unistd.h>
static struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"verbose", no_argument, NULL, 'v'},
{0, 0, 0, 0}
};
void usage(int exit_code) {
puts("Usage: exchange [-v] PATH1 PATH2\n"
" or: exchange -h|--help\n"
"atomically exchange names of two files or directories\n"
"\n"
"Options:\n"
" -h, --help shows help text\n"
" -v, --verbose produce verbose output");
exit(exit_code);
}
int main(int argc, char **argv) {
int c;
bool verbose = false;
char **paths;
int ret;
while ((c = getopt_long(argc, argv, "hv", long_options, NULL)) != -1) {
switch (c) {
case 'h':
usage(EXIT_SUCCESS);
case 'v':
verbose = true;
break;
default:
usage(EXIT_FAILURE);
}
}
if (argc - optind != 2) {
puts("Exactly two paths are required.\n");
usage(EXIT_FAILURE);
}
paths = argv + optind;
if (verbose) {
printf("Exchanging paths %s and %s\n", paths[0], paths[1]);
}
// Atomically exchange the two paths. If paths are not absolute, consider
// them relative to the current working directory
#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
ret = renameat2(AT_FDCWD, paths[0], AT_FDCWD, paths[1], RENAME_EXCHANGE);
#else
ret = syscall(SYS_renameat2, AT_FDCWD, paths[0], AT_FDCWD, paths[1], RENAME_EXCHANGE);
#endif
if (ret == -1) {
perror("exchange: could not exchange the two paths");
exit(EXIT_FAILURE);
}
if (verbose) {
puts("Paths exchanged successfully");
}
return EXIT_SUCCESS;
}