version 0.1.10
[fms.git] / src / fmsdaemon.cpp
1 #include "../include/fmsdaemon.h"\r
2 \r
3 #include <cstdio>\r
4 #include <cstdlib>\r
5 #include <sys/types.h>\r
6 #ifndef _WIN32\r
7         #include <unistd.h>\r
8         #include <sys/stat.h>\r
9 #endif\r
10 \r
11 #ifdef XMEM\r
12         #include <xmem.h>\r
13 #endif\r
14 \r
15 /*\r
16         modified from http://www-theorie.physik.unizh.ch/~dpotter/howto/daemonize\r
17 */\r
18 void Daemonize()\r
19 {\r
20 #ifndef _WIN32\r
21     pid_t pid, sid;\r
22 \r
23     /* already a daemon */\r
24     if ( getppid() == 1 ) return;\r
25 \r
26     /* Fork off the parent process */\r
27     pid = fork();\r
28     if (pid < 0) {\r
29         exit(EXIT_FAILURE);\r
30     }\r
31     /* If we got a good PID, then we can exit the parent process. */\r
32     if (pid > 0) {\r
33         exit(EXIT_SUCCESS);\r
34     }\r
35 \r
36     /* At this point we are executing as the child process */\r
37 \r
38     /* Change the file mode mask */\r
39     umask(0);\r
40 \r
41     /* Create a new SID for the child process */\r
42     sid = setsid();\r
43     if (sid < 0) {\r
44         exit(EXIT_FAILURE);\r
45     }\r
46 \r
47     /* Redirect standard files to /dev/null */\r
48     freopen( "/dev/null", "r", stdin);\r
49     freopen( "/dev/null", "w", stdout);\r
50     freopen( "/dev/null", "w", stderr);\r
51 #endif\r
52 }\r