3750fc3433448a92cbb5b78e88330cc0d9e71d78
[musl] / src / linux / daemon.c
1 #include <fcntl.h>
2 #include <unistd.h>
3
4 int daemon(int nochdir, int noclose)
5 {
6         int fd;
7
8         switch(fork()) {
9         case 0: break;
10         case -1: return -1;
11         default: _exit(0);
12         }
13
14         if (setsid() < 0) return -1;
15
16         switch(fork()) {
17         case 0: break;
18         case -1: return -1;
19         default: _exit(0);
20         }
21
22         if (!nochdir && chdir("/"))
23                 return -1;
24         if (!noclose) {
25                 int failed = 0;
26                 if ((fd = open("/dev/null", O_RDWR)) < 0) return -1;
27                 if (dup2(fd, 0) < 0 || dup2(fd, 1) < 0 || dup2(fd, 2) < 0)
28                         failed++;
29                 if (fd > 2) close(fd);
30                 if (failed) return -1;
31         }
32
33         return 0;
34 }