Fix sequence logic bug, and satisfies() logic fix/cleanup.
[ccan] / ccan / daemonize / test / run.c
1 #include <ccan/daemonize/daemonize.h>
2 #include <ccan/daemonize/daemonize.c>
3 #include <ccan/tap/tap.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <err.h>
7 #include <errno.h>
8
9 struct child_data {
10         pid_t pid;
11         pid_t ppid;
12         bool in_root_dir;
13         int read_from_stdin, write_to_stdout, write_to_stderr;
14 };
15
16 int main(int argc, char *argv[])
17 {
18         int fds[2];
19         struct child_data daemonized;
20         pid_t pid;
21
22         plan_tests(6);
23
24         if (pipe(fds) != 0)
25                 err(1, "Failed pipe");
26
27         /* Since daemonize forks and parent exits, we need to fork
28          * that parent. */
29         pid = fork();
30         if (pid == -1)
31                 err(1, "Failed fork");
32
33         if (pid == 0) {
34                 char buffer[2];
35                 pid = getpid();
36                 daemonize();
37                 daemonized.pid = getpid();
38                 daemonized.in_root_dir = (getcwd(buffer, 2) != NULL);
39                 daemonized.read_from_stdin
40                         = read(STDIN_FILENO, buffer, 1) == -1 ? errno : 0;
41                 daemonized.write_to_stdout
42                         = write(STDOUT_FILENO, buffer, 1) == -1 ? errno : 0;
43                 daemonized.write_to_stderr
44                         = write(STDERR_FILENO, buffer, 1) == -1 ? errno : 0;
45
46                 /* Make sure parent exits. */
47                 while (getppid() == pid)
48                         sleep(1);
49                 daemonized.ppid = getppid();
50                 if (write(fds[1], &daemonized, sizeof(daemonized))
51                     != sizeof(daemonized))
52                         exit(1);
53                 exit(0);
54         }
55
56         if (read(fds[0], &daemonized, sizeof(daemonized)) != sizeof(daemonized))
57                 err(1, "Failed read");
58
59         ok1(daemonized.pid != pid);
60         ok1(daemonized.ppid == 1);
61         ok1(daemonized.in_root_dir);
62         ok1(daemonized.read_from_stdin == EBADF);
63         ok1(daemonized.write_to_stdout == EBADF);
64         ok1(daemonized.write_to_stderr == EBADF);
65
66         return exit_status();
67 }