2 * This code is mainly taken from Doug Potter's page
4 * http://www-theorie.physik.unizh.ch/~dpotter/howto/daemonize
6 * I contacted him 2007-04-16 about the license for the original code,
7 * he replied it is Public Domain. Use the URL above to get the original
8 * Public Domain version if you want it.
10 * This version is LGPL2 and is (c)2006 - 2013 Andy Green <andy@warmcat.com>
17 #include <sys/types.h>
24 static int pid_daemon;
25 static char lock_path[PATH_MAX];
27 static void child_handler(int signum)
34 case SIGALRM: /* timedout daemonizing */
38 case SIGUSR1: /* positive confirmation we daemonized well */
39 /* Create the lock file as the current user */
41 fd = open(lock_path, O_TRUNC | O_RDWR | O_CREAT, 0640);
43 fprintf(stderr, "unable to create lock"
44 " file %s, code=%d (%s)",
45 lock_path, errno, strerror(errno));
48 sprintf(sz, "%u", pid_daemon);
49 write(fd, sz, strlen(sz));
53 case SIGCHLD: /* daemonization failed */
60 * You just need to call this from your main(), when it
61 * returns you are all set "in the background" decoupled
62 * from the console you were started from.
64 * The process context you called from has been terminated then.
67 int lws_daemonize(const char *_lock_path)
71 /* already a daemon */
75 strncpy(lock_path, _lock_path, sizeof lock_path);
76 lock_path[sizeof(lock_path) - 1] = '\0';
78 /* Trap signals that we expect to recieve */
79 signal(SIGCHLD, child_handler); /* died */
80 signal(SIGUSR1, child_handler); /* was happy */
81 signal(SIGALRM, child_handler); /* timeout daemonizing */
83 /* Fork off the parent process */
86 fprintf(stderr, "unable to fork daemon, code=%d (%s)",
87 errno, strerror(errno));
91 /* If we got a good PID, then we can exit the parent process. */
95 * Wait for confirmation signal from the child via
96 * SIGCHILD / USR1, or for two seconds to elapse
97 * (SIGALRM). pause() should not return.
102 /* should not be reachable */
106 /* At this point we are executing as the child process */
109 /* Cancel certain signals */
110 signal(SIGCHLD, SIG_DFL); /* A child process dies */
111 signal(SIGTSTP, SIG_IGN); /* Various TTY signals */
112 signal(SIGTTOU, SIG_IGN);
113 signal(SIGTTIN, SIG_IGN);
114 signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */
116 /* Change the file mode mask */
119 /* Create a new SID for the child process */
123 "unable to create a new session, code %d (%s)",
124 errno, strerror(errno));
129 * Change the current working directory. This prevents the current
130 * directory from being locked; hence not being able to remove it.
132 if ((chdir("/")) < 0) {
134 "unable to change directory to %s, code %d (%s)",
135 "/", errno, strerror(errno));
139 /* Redirect standard files to /dev/null */
140 freopen("/dev/null", "r", stdin);
141 freopen("/dev/null", "w", stdout);
142 freopen("/dev/null", "w", stderr);
144 /* Tell the parent process that we are A-okay */
145 kill(parent, SIGUSR1);
147 /* return to continue what is now "the daemon" */