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