license clarification and test apps CC zero
[platform/upstream/libwebsockets.git] / lib / daemonize.c
1 /*
2  * This code is mainly taken from Doug Potter's page
3  *
4  * http://www-theorie.physik.unizh.ch/~dpotter/howto/daemonize
5  *
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.
9  *
10  * This version is LGPL2.1+SLE like the rest of libwebsockets and is
11  * Copyright (c)2006 - 2013 Andy Green <andy@warmcat.com>
12  */
13
14 #include <stdlib.h>
15 #include <string.h>
16 #include <stdio.h>
17 #include <signal.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <limits.h>
22 #include <unistd.h>
23 #include <errno.h>
24
25 #include "private-libwebsockets.h"
26
27 int pid_daemon;
28 static char *lock_path;
29
30 int get_daemonize_pid()
31 {
32         return pid_daemon;
33 }
34
35 static void
36 child_handler(int signum)
37 {
38         int fd, len, sent;
39         char sz[20];
40
41         switch (signum) {
42
43         case SIGALRM: /* timed out daemonizing */
44                 exit(1);
45                 break;
46
47         case SIGUSR1: /* positive confirmation we daemonized well */
48                 /* Create the lock file as the current user */
49
50                 fd = open(lock_path, O_TRUNC | O_RDWR | O_CREAT, 0640);
51                 if (fd < 0) {
52                         fprintf(stderr,
53                            "unable to create lock file %s, code=%d (%s)\n",
54                                 lock_path, errno, strerror(errno));
55                         exit(1);
56                 }
57                 len = sprintf(sz, "%u", pid_daemon);
58                 sent = write(fd, sz, len);
59                 if (sent != len)
60                         fprintf(stderr,
61                           "unable to write pid to lock file %s, code=%d (%s)\n",
62                                              lock_path, errno, strerror(errno));
63
64                 close(fd);
65                 exit(!!(sent == len));
66
67         case SIGCHLD: /* daemonization failed */
68                 exit(1);
69                 break;
70         }
71 }
72
73 static void lws_daemon_closing(int sigact)
74 {
75         if (getpid() == pid_daemon)
76                 if (lock_path) {
77                         unlink(lock_path);
78                         lws_free_set_NULL(lock_path);
79                 }
80
81         kill(getpid(), SIGKILL);
82 }
83
84 /*
85  * You just need to call this from your main(), when it
86  * returns you are all set "in the background" decoupled
87  * from the console you were started from.
88  *
89  * The process context you called from has been terminated then.
90  */
91
92 LWS_VISIBLE int
93 lws_daemonize(const char *_lock_path)
94 {
95         struct sigaction act;
96         pid_t sid, parent;
97         int n, fd, ret;
98         char buf[10];
99
100         /* already a daemon */
101         if (getppid() == 1)
102                 return 1;
103
104         fd = open(_lock_path, O_RDONLY);
105         if (fd >= 0) {
106                 n = read(fd, buf, sizeof(buf));
107                 close(fd);
108                 if (n) {
109                         n = atoi(buf);
110                         ret = kill(n, 0);
111                         if (ret >= 0) {
112                                 fprintf(stderr,
113                                      "Daemon already running from pid %d\n", n);
114                                 exit(1);
115                         }
116                         fprintf(stderr,
117                             "Removing stale lock file %s from dead pid %d\n",
118                                                                  _lock_path, n);
119                         unlink(lock_path);
120                 }
121         }
122
123         n = strlen(_lock_path) + 1;
124         lock_path = lws_malloc(n);
125         if (!lock_path) {
126                 fprintf(stderr, "Out of mem in lws_daemonize\n");
127                 return 1;
128         }
129         strcpy(lock_path, _lock_path);
130
131         /* Trap signals that we expect to receive */
132         signal(SIGCHLD, child_handler); /* died */
133         signal(SIGUSR1, child_handler); /* was happy */
134         signal(SIGALRM, child_handler); /* timeout daemonizing */
135
136         /* Fork off the parent process */
137         pid_daemon = fork();
138         if (pid_daemon < 0) {
139                 fprintf(stderr, "unable to fork daemon, code=%d (%s)",
140                     errno, strerror(errno));
141                 exit(1);
142         }
143
144         /* If we got a good PID, then we can exit the parent process. */
145         if (pid_daemon > 0) {
146
147                 /*
148                  * Wait for confirmation signal from the child via
149                  * SIGCHILD / USR1, or for two seconds to elapse
150                  * (SIGALRM).  pause() should not return.
151                  */
152                 alarm(2);
153
154                 pause();
155                 /* should not be reachable */
156                 exit(1);
157         }
158
159         /* At this point we are executing as the child process */
160         parent = getppid();
161         pid_daemon = getpid();
162
163         /* Cancel certain signals */
164         signal(SIGCHLD, SIG_DFL); /* A child process dies */
165         signal(SIGTSTP, SIG_IGN); /* Various TTY signals */
166         signal(SIGTTOU, SIG_IGN);
167         signal(SIGTTIN, SIG_IGN);
168         signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */
169
170         /* Change the file mode mask */
171         umask(0);
172
173         /* Create a new SID for the child process */
174         sid = setsid();
175         if (sid < 0) {
176                 fprintf(stderr,
177                         "unable to create a new session, code %d (%s)",
178                         errno, strerror(errno));
179                 exit(1);
180         }
181
182         /*
183          * Change the current working directory.  This prevents the current
184          * directory from being locked; hence not being able to remove it.
185          */
186         if (chdir("/") < 0) {
187                 fprintf(stderr,
188                         "unable to change directory to %s, code %d (%s)",
189                         "/", errno, strerror(errno));
190                 exit(1);
191         }
192
193         /* Redirect standard files to /dev/null */
194         if (!freopen("/dev/null", "r", stdin))
195                 fprintf(stderr, "unable to freopen() stdin, code %d (%s)",
196                                                        errno, strerror(errno));
197
198         if (!freopen("/dev/null", "w", stdout))
199                 fprintf(stderr, "unable to freopen() stdout, code %d (%s)",
200                                                        errno, strerror(errno));
201
202         if (!freopen("/dev/null", "w", stderr))
203                 fprintf(stderr, "unable to freopen() stderr, code %d (%s)",
204                                                        errno, strerror(errno));
205
206         /* Tell the parent process that we are A-okay */
207         kill(parent, SIGUSR1);
208
209         act.sa_handler = lws_daemon_closing;
210         sigemptyset(&act.sa_mask);
211         act.sa_flags = 0;
212
213         sigaction(SIGTERM, &act, NULL);
214
215         /* return to continue what is now "the daemon" */
216
217         return 0;
218 }
219