1 #include <ccan/pipecmd/pipecmd.h>
2 /* Include the C files directly. */
3 #include <ccan/pipecmd/pipecmd.c>
4 #include <ccan/tap/tap.h>
9 int main(int argc, char *argv[])
12 int fd, oldfd, status;
14 char template[] = "/tmp/run-preserve.XXXXXX";
16 /* We call ourselves, to test pipe. */
18 if (strcmp(argv[1], "out") == 0) {
19 if (write(STDOUT_FILENO, buf, sizeof(buf)) != sizeof(buf))
21 } else if (strcmp(argv[1], "in") == 0) {
22 if (read(STDIN_FILENO, buf, sizeof(buf)) != sizeof(buf))
24 if (memcmp(buf, "test", sizeof(buf)) != 0)
26 } else if (strcmp(argv[1], "err") == 0) {
27 if (write(STDERR_FILENO, buf, sizeof(buf)) != sizeof(buf))
34 /* This is how many tests you plan to run */
37 /* Preserve stdin test. */
38 fd = mkstemp(template);
39 ok1(write(fd, buf, sizeof(buf)) == sizeof(buf));
41 ok1(dup2(fd, STDIN_FILENO) == STDIN_FILENO);
42 ok1(lseek(STDIN_FILENO, 0, SEEK_SET) == 0);
43 child = pipecmd(&pipecmd_preserve, NULL, NULL, argv[0], "in", NULL);
46 ok1(waitpid(child, &status, 0) == child);
47 ok1(WIFEXITED(status));
48 ok1(WEXITSTATUS(status) == 0);
52 /* Preserve stdout test */
53 fd = open(template, O_WRONLY|O_TRUNC);
55 oldfd = dup(STDOUT_FILENO);
56 /* Can't use OK after this, since we mug stdout */
57 if (dup2(fd, STDOUT_FILENO) != STDOUT_FILENO)
59 child = pipecmd(NULL, &pipecmd_preserve, NULL, argv[0], "out", NULL);
63 dup2(oldfd, STDOUT_FILENO);
65 ok1(waitpid(child, &status, 0) == child);
66 ok1(WIFEXITED(status));
67 ok1(WEXITSTATUS(status) == 0);
69 fd = open(template, O_RDONLY);
70 ok1(read(fd, buf, sizeof(buf)) == sizeof(buf));
72 ok1(memcmp(buf, "test", sizeof(buf)) == 0);
74 /* Preserve stderr test. */
75 fd = open(template, O_WRONLY|O_TRUNC);
77 oldfd = dup(STDERR_FILENO);
78 ok1(dup2(fd, STDERR_FILENO) == STDERR_FILENO);
79 child = pipecmd(NULL, NULL, &pipecmd_preserve, argv[0], "err", NULL);
84 ok1(dup2(oldfd, STDERR_FILENO));
85 ok1(waitpid(child, &status, 0) == child);
86 ok1(WIFEXITED(status));
87 ok1(WEXITSTATUS(status) == 0);
90 fd = open(template, O_RDONLY);
91 ok1(read(fd, buf, sizeof(buf)) == sizeof(buf));
93 ok1(memcmp(buf, "test", sizeof(buf)) == 0);
96 /* This exits depending on whether all tests passed */