daemonize / daemon_with_notify: ignore Ubuntu 13.10 brain death.
[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(5);
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                 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 #if 0   /* Believe it or not, this fails under Ubuntu 13.10 (Upstart) */
68         ok1(daemonized.ppid == 1);
69 #endif
70         ok1(daemonized.in_root_dir);
71         ok1(daemonized.read_from_stdin == EBADF);
72         ok1(daemonized.write_to_stdout == EBADF);
73         ok1(daemonized.write_to_stderr == 0);
74
75         return exit_status();
76 }