]> git.ozlabs.org Git - ccan/blob - ccan/daemonize/daemonize.c
daemonize: set stderr to /dev/null.
[ccan] / ccan / daemonize / daemonize.c
1 #include <ccan/daemonize/daemonize.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7
8 /* This code is based on Stevens Advanced Programming in the UNIX
9  * Environment. */
10 bool daemonize(void)
11 {
12         pid_t pid;
13
14         /* Separate from our parent via fork, so init inherits us. */
15         if ((pid = fork()) < 0)
16                 return false;
17         if (pid != 0)
18                 exit(0);
19
20         /* Don't hold files open. */
21         close(STDIN_FILENO);
22         close(STDOUT_FILENO);
23         close(STDERR_FILENO);
24
25         /* Many routines write to stderr; that can cause chaos if used
26          * for something else, so set it here. */
27         if (open("/dev/null", O_WRONLY) != 0)
28                 return false;
29         if (dup2(0, STDERR_FILENO) != STDERR_FILENO)
30                 return false;
31         close(0);
32
33         /* Session leader so ^C doesn't whack us. */
34         setsid();
35         /* Move off any mount points we might be in. */
36         if (chdir("/") != 0)
37                 return false;
38
39         /* Discard our parent's old-fashioned umask prejudices. */
40         umask(0);
41         return true;
42 }