chiark / gitweb /
sys/t/mdup-test.c: Cope with the idea of arguments which aren't fd pairs.
[mLib] / sys / t / mdup-test.c
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, j;
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 = 1, j = 0; i < argc; i++) {
26     if (j >= MAXFD) { fprintf(stderr, "too many\n"); exit(1); }
27     if (sscanf(argv[i], "%d:%d", &fds[j].cur, &fds[j].want) < 2 ||
28         fds[j].cur >= MAXFD)
29       { fprintf(stderr, "bad syntax\n"); exit(1); }
30     j++;
31   }
32   n = j;
33   for (i = 0; i < MAXFD; i++) flag[i] = -1;
34   for (i = 0; i < n; i++) {
35     fd = fds[i].cur;
36     if (flag[fd] >= 0)
37       ino[i] = ino[flag[fd]];
38     else {
39       flag[fd] = i;
40       if ((fd2 = open(",delete-me",
41                       O_WRONLY | O_CREAT | O_EXCL,
42                       0700)) < 0)
43         fail("creat");
44       unlink(",delete-me");
45       if (fd2 != fd) { if (dup2(fd2, fd) < 0) fail("dup2"); close(fd2); }
46       if (fstat(fd, &st)) fail("fstat");
47       ino[i] = st.st_ino;
48     }
49   }
50
51   if (mdup(fds, n)) fail("mdup");
52
53   for (i = 0; i < n; i++) {
54     fd = fds[i].cur;
55     if (fds[i].want != -1 && fds[i].want != fd) {
56       printf("fd %d[%d] != %d\n", fd, i, fds[i].want);
57       win = 0;
58     } else if (fstat(fd, &st)) {
59       printf("fstat %d[%d] failed: %s\n", fd, i, strerror(errno));
60       win = 0;
61     } else if (st.st_ino != ino[i]) {
62       printf("ino %d[%d] wrong\n", fd, i);
63       win = 0;
64     }
65   }
66
67   return (!win);
68 }