]> git.ozlabs.org Git - ccan/blob - ccan/daemon_with_notify/test/run.c
base64: fix for unsigned chars (e.g. ARM).
[ccan] / ccan / daemon_with_notify / test / run.c
1 #include <ccan/daemon_with_notify/daemon_with_notify.h>
2 #include <ccan/daemon_with_notify/daemon_with_notify.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         int 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(0, 0, 1);
38                 daemon_is_ready();
39                 /* Keep valgrind happy about uninitialized bytes. */
40                 memset(&daemonized, 0, sizeof(daemonized));
41                 daemonized.pid = getpid();
42                 daemonized.in_root_dir = (getcwd(buffer, 2) != NULL);
43                 daemonized.read_from_stdin
44                         = read(STDIN_FILENO, buffer, 1) == -1 ? errno : 0;
45                 daemonized.write_to_stdout
46                         = write(STDOUT_FILENO, buffer, 1) == -1 ? errno : 0;
47                 if (write(STDERR_FILENO, buffer, 1) != 1) {
48                         daemonized.write_to_stderr = errno;
49                         if (daemonized.write_to_stderr == 0)
50                                 daemonized.write_to_stderr = -1;
51                 } else
52                         daemonized.write_to_stderr = 0;
53
54                 /* Make sure parent exits. */
55                 while (getppid() == pid)
56                         sleep(1);
57                 daemonized.ppid = getppid();
58                 if (write(fds[1], &daemonized, sizeof(daemonized))
59                     != sizeof(daemonized))
60                         exit(1);
61                 exit(0);
62         }
63
64         if (read(fds[0], &daemonized, sizeof(daemonized)) != sizeof(daemonized))
65                 err(1, "Failed read");
66
67         ok1(daemonized.pid != pid);
68 #if 0   /* Believe it or not, this fails under Ubuntu 13.10 (Upstart) */
69         ok1(daemonized.ppid == 1);
70 #endif
71         ok1(daemonized.in_root_dir);
72         ok1(daemonized.read_from_stdin == 0);
73         ok1(daemonized.write_to_stdout == 0);
74         ok1(daemonized.write_to_stderr == 0);
75
76         return exit_status();
77 }