c86f214bcae6e3fcfb2901e436971471e21e2479
[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 #include <string.h>
9
10 struct child_data {
11         pid_t pid;
12         pid_t ppid;
13         bool in_root_dir;
14         int read_from_stdin, write_to_stdout, write_to_stderr;
15 };
16
17 int main(int argc, char *argv[])
18 {
19         int fds[2];
20         struct child_data daemonized;
21         pid_t pid;
22
23         plan_tests(6);
24
25         if (pipe(fds) != 0)
26                 err(1, "Failed pipe");
27
28         /* Since daemonize forks and parent exits, we need to fork
29          * that parent. */
30         pid = fork();
31         if (pid == -1)
32                 err(1, "Failed fork");
33
34         if (pid == 0) {
35                 char buffer[2];
36                 pid = getpid();
37                 daemonize();
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                 daemonized.write_to_stderr
47                         = write(STDERR_FILENO, buffer, 1) == -1 ? errno : 0;
48
49                 /* Make sure parent exits. */
50                 while (getppid() == pid)
51                         sleep(1);
52                 daemonized.ppid = getppid();
53                 if (write(fds[1], &daemonized, sizeof(daemonized))
54                     != sizeof(daemonized))
55                         exit(1);
56                 exit(0);
57         }
58
59         if (read(fds[0], &daemonized, sizeof(daemonized)) != sizeof(daemonized))
60                 err(1, "Failed read");
61
62         ok1(daemonized.pid != pid);
63         ok1(daemonized.ppid == 1);
64         ok1(daemonized.in_root_dir);
65         ok1(daemonized.read_from_stdin == EBADF);
66         ok1(daemonized.write_to_stdout == EBADF);
67         ok1(daemonized.write_to_stderr == EBADF);
68
69         return exit_status();
70 }