Commit | Line | Data |
---|---|---|
b317b99d MW |
1 | #include <errno.h> |
2 | #include <stdio.h> | |
3 | #include <stdlib.h> | |
4 | #include <string.h> | |
5 | #include <unistd.h> | |
6 | #include <sys/types.h> | |
7 | #include <sys/stat.h> | |
8 | #include <fcntl.h> | |
9 | #include "mdup.h" | |
10 | ||
11 | #define MAXFD 256 | |
12 | ||
13 | static void fail(const char *what) { perror(what); exit(1); } | |
14 | ||
15 | int main(int argc, char *argv[]) | |
16 | { | |
7ff43cd7 | 17 | int i, n, j; |
b317b99d MW |
18 | int fd, fd2; |
19 | struct stat st; | |
20 | int ino[MAXFD]; | |
21 | int flag[MAXFD]; | |
22 | mdup_fd fds[MAXFD]; | |
23 | int win = 1; | |
2793197b | 24 | int verbose = 0; |
b317b99d | 25 | |
7ff43cd7 | 26 | for (i = 1, j = 0; i < argc; i++) { |
2793197b | 27 | if (strcmp(argv[i], "-v") == 0) { verbose++; continue; } |
7ff43cd7 MW |
28 | if (j >= MAXFD) { fprintf(stderr, "too many\n"); exit(1); } |
29 | if (sscanf(argv[i], "%d:%d", &fds[j].cur, &fds[j].want) < 2 || | |
30 | fds[j].cur >= MAXFD) | |
d428ae6d | 31 | { fprintf(stderr, "bad syntax\n"); exit(1); } |
7ff43cd7 | 32 | j++; |
b317b99d | 33 | } |
7ff43cd7 | 34 | n = j; |
b317b99d MW |
35 | for (i = 0; i < MAXFD; i++) flag[i] = -1; |
36 | for (i = 0; i < n; i++) { | |
37 | fd = fds[i].cur; | |
2793197b | 38 | if (flag[fd] >= 0) { |
b317b99d | 39 | ino[i] = ino[flag[fd]]; |
2793197b MW |
40 | if (verbose) |
41 | printf("exist fd %d[%d] = ino %lu\n", fd, i, (unsigned long)ino[i]); | |
42 | } else { | |
b317b99d MW |
43 | flag[fd] = i; |
44 | if ((fd2 = open(",delete-me", | |
45 | O_WRONLY | O_CREAT | O_EXCL, | |
46 | 0700)) < 0) | |
47 | fail("creat"); | |
48 | unlink(",delete-me"); | |
d428ae6d | 49 | if (fd2 != fd) { if (dup2(fd2, fd) < 0) fail("dup2"); close(fd2); } |
b317b99d MW |
50 | if (fstat(fd, &st)) fail("fstat"); |
51 | ino[i] = st.st_ino; | |
2793197b MW |
52 | if (verbose) |
53 | printf("open fd %d[%d] = ino %lu\n", fd, i, (unsigned long)ino[i]); | |
b317b99d MW |
54 | } |
55 | } | |
56 | ||
57 | if (mdup(fds, n)) fail("mdup"); | |
58 | ||
59 | for (i = 0; i < n; i++) { | |
60 | fd = fds[i].cur; | |
61 | if (fds[i].want != -1 && fds[i].want != fd) { | |
62 | printf("fd %d[%d] != %d\n", fd, i, fds[i].want); | |
63 | win = 0; | |
64 | } else if (fstat(fd, &st)) { | |
65 | printf("fstat %d[%d] failed: %s\n", fd, i, strerror(errno)); | |
66 | win = 0; | |
67 | } else if (st.st_ino != ino[i]) { | |
2793197b MW |
68 | if (!verbose) printf("ino %d[%d] wrong\n", fd, i); |
69 | else printf("ino %d[%d] = %lu != %lu\n", fd, i, | |
70 | (unsigned long)(st.st_ino), (unsigned long)ino[i]); | |
b317b99d MW |
71 | win = 0; |
72 | } | |
73 | } | |
74 | ||
75 | return (!win); | |
76 | } |