update test case copied from daemonize to use some of daemon-with-notify features
[ccan] / ccan / daemon-with-notify / test / run.c
1 #include <ccan/daemon-with-notify/daemon.h>
2 #include <ccan/tap/tap.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <err.h>
6 #include <errno.h>
7 #include <string.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(0, 0, 1);
37                 daemon_is_ready();
38                 /* Keep valgrind happy about uninitialized bytes. */
39                 memset(&daemonized, 0, sizeof(daemonized));
40                 daemonized.pid = getpid();
41                 daemonized.in_root_dir = (getcwd(buffer, 2) != NULL);
42                 daemonized.read_from_stdin
43                         = read(STDIN_FILENO, buffer, 1) == -1 ? errno : 0;
44                 daemonized.write_to_stdout
45                         = write(STDOUT_FILENO, buffer, 1) == -1 ? errno : 0;
46                 if (write(STDERR_FILENO, buffer, 1) != 1) {
47                         daemonized.write_to_stderr = errno;
48                         if (daemonized.write_to_stderr == 0)
49                                 daemonized.write_to_stderr = -1;
50                 } else
51                         daemonized.write_to_stderr = 0;
52
53                 /* Make sure parent exits. */
54                 while (getppid() == pid)
55                         sleep(1);
56                 daemonized.ppid = getppid();
57                 if (write(fds[1], &daemonized, sizeof(daemonized))
58                     != sizeof(daemonized))
59                         exit(1);
60                 exit(0);
61         }
62
63         if (read(fds[0], &daemonized, sizeof(daemonized)) != sizeof(daemonized))
64                 err(1, "Failed read");
65
66         ok1(daemonized.pid != pid);
67         ok1(daemonized.ppid == 1);
68         ok1(daemonized.in_root_dir);
69         ok1(daemonized.read_from_stdin == EBADF);
70         ok1(daemonized.write_to_stdout == EBADF);
71         ok1(daemonized.write_to_stderr == 0);
72
73         return exit_status();
74 }