0
|
1 /*Add by Sergey Shapovalov */
|
|
2 #include <unistd.h>
|
|
3 #include <stdlib.h>
|
|
4 #include <fcntl.h>
|
|
5 #include <signal.h>
|
|
6 #include <sys/types.h>
|
|
7 #include <sys/wait.h>
|
|
8 #include <errno.h>
|
|
9
|
|
10 /* closeall() -- close all FDs >= a specified value */
|
|
11
|
|
12 void closeall(int fd)
|
|
13 {
|
|
14 int fdlimit = sysconf(_SC_OPEN_MAX);
|
|
15
|
|
16 while (fd < fdlimit)
|
|
17 close(fd++);
|
|
18 }
|
|
19
|
|
20 /* daemon() - detach process from user and disappear into the background
|
|
21 * returns -1 on failure, but you can't do much except exit in that case
|
|
22 * since we may already have forked. This is based on the BSD version,
|
|
23 * so the caller is responsible for things like the umask, etc.
|
|
24 */
|
|
25
|
|
26 /* believed to work on all Posix systems */
|
|
27
|
|
28 int daemon(int nochdir, int noclose)
|
|
29 {
|
|
30 switch (fork())
|
|
31 {
|
|
32 case 0: break;
|
|
33 case -1: return -1;
|
|
34 default: _exit(0); /* exit the original process */
|
|
35 }
|
|
36
|
|
37 if (setsid() < 0) /* shoudn't fail */
|
|
38 return -1;
|
|
39
|
|
40 /* dyke out this switch if you want to acquire a control tty in */
|
|
41 /* the future -- not normally advisable for daemons */
|
|
42
|
|
43 switch (fork())
|
|
44 {
|
|
45 case 0: break;
|
|
46 case -1: return -1;
|
|
47 default: _exit(0);
|
|
48 }
|
|
49
|
|
50 if (!nochdir)
|
|
51 chdir("/");
|
|
52
|
|
53 if (!noclose)
|
|
54 {
|
|
55 closeall(0);
|
|
56 open("/dev/null",O_RDWR);
|
|
57 dup(0); dup(0);
|
|
58 }
|
|
59
|
|
60 return 0;
|
|
61 }
|