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