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 | { | |
17 | int i, n; | |
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; | |
24 | ||
25 | for (i = 0; i < argc - 1; i++) { | |
26 | if (i >= MAXFD) { | |
27 | fprintf(stderr, "too many\n"); | |
28 | exit(1); | |
29 | } | |
30 | if (sscanf(argv[i + 1], "%d:%d", &fds[i].cur, &fds[i].want) < 2 || | |
31 | fds[i].cur >= MAXFD) { | |
32 | fprintf(stderr, "bad syntax\n"); | |
33 | exit(1); | |
34 | } | |
35 | } | |
36 | n = argc - 1; | |
37 | for (i = 0; i < MAXFD; i++) flag[i] = -1; | |
38 | for (i = 0; i < n; i++) { | |
39 | fd = fds[i].cur; | |
40 | if (flag[fd] >= 0) | |
41 | ino[i] = ino[flag[fd]]; | |
42 | else { | |
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"); | |
49 | if (fd2 != fd) { | |
50 | if (dup2(fd2, fd) < 0) fail("dup2"); | |
51 | close(fd2); | |
52 | } | |
53 | if (fstat(fd, &st)) fail("fstat"); | |
54 | ino[i] = st.st_ino; | |
55 | } | |
56 | } | |
57 | ||
58 | if (mdup(fds, n)) fail("mdup"); | |
59 | ||
60 | for (i = 0; i < n; i++) { | |
61 | fd = fds[i].cur; | |
62 | if (fds[i].want != -1 && fds[i].want != fd) { | |
63 | printf("fd %d[%d] != %d\n", fd, i, fds[i].want); | |
64 | win = 0; | |
65 | } else if (fstat(fd, &st)) { | |
66 | printf("fstat %d[%d] failed: %s\n", fd, i, strerror(errno)); | |
67 | win = 0; | |
68 | } else if (st.st_ino != ino[i]) { | |
69 | printf("ino %d[%d] wrong\n", fd, i); | |
70 | win = 0; | |
71 | } | |
72 | } | |
73 | ||
74 | return (!win); | |
75 | } |