OLD | NEW |
1 #define _GNU_SOURCE | 1 #define _GNU_SOURCE |
2 #include <fcntl.h> | 2 #include <fcntl.h> |
3 #include <unistd.h> | 3 #include <unistd.h> |
4 | 4 |
5 int daemon(int nochdir, int noclose) | 5 int daemon(int nochdir, int noclose) { |
6 { | 6 if (!nochdir && chdir("/")) |
7 » if (!nochdir && chdir("/")) | 7 return -1; |
8 » » return -1; | 8 if (!noclose) { |
9 » if (!noclose) { | 9 int fd, failed = 0; |
10 » » int fd, failed = 0; | 10 if ((fd = open("/dev/null", O_RDWR)) < 0) |
11 » » if ((fd = open("/dev/null", O_RDWR)) < 0) return -1; | 11 return -1; |
12 » » if (dup2(fd, 0) < 0 || dup2(fd, 1) < 0 || dup2(fd, 2) < 0) | 12 if (dup2(fd, 0) < 0 || dup2(fd, 1) < 0 || dup2(fd, 2) < 0) |
13 » » » failed++; | 13 failed++; |
14 » » if (fd > 2) close(fd); | 14 if (fd > 2) |
15 » » if (failed) return -1; | 15 close(fd); |
16 » } | 16 if (failed) |
| 17 return -1; |
| 18 } |
17 | 19 |
18 » switch(fork()) { | 20 switch (fork()) { |
19 » case 0: break; | 21 case 0: |
20 » case -1: return -1; | 22 break; |
21 » default: _exit(0); | 23 case -1: |
22 » } | 24 return -1; |
| 25 default: |
| 26 _exit(0); |
| 27 } |
23 | 28 |
24 » if (setsid() < 0) return -1; | 29 if (setsid() < 0) |
| 30 return -1; |
25 | 31 |
26 » switch(fork()) { | 32 switch (fork()) { |
27 » case 0: break; | 33 case 0: |
28 » case -1: return -1; | 34 break; |
29 » default: _exit(0); | 35 case -1: |
30 » } | 36 return -1; |
| 37 default: |
| 38 _exit(0); |
| 39 } |
31 | 40 |
32 » return 0; | 41 return 0; |
33 } | 42 } |
OLD | NEW |