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