Revert changes in daemonize.c from commit 22d6f39e7fb270d0c011bae820d2f8adc8b19061
[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(0);
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(5);
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(0);
66                 //!!(sent == len));
67
68         case SIGCHLD: /* daemonization failed */
69                 exit(6);
70                 break;
71         }
72 }
73
74 static void lws_daemon_closing(int sigact)
75 {
76         if (getpid() == pid_daemon)
77                 if (lock_path) {
78                         unlink(lock_path);
79                         lws_free_set_NULL(lock_path);
80                 }
81
82         kill(getpid(), SIGKILL);
83 }
84
85 /*
86  * You just need to call this from your main(), when it
87  * returns you are all set "in the background" decoupled
88  * from the console you were started from.
89  *
90  * The process context you called from has been terminated then.
91  */
92
93 LWS_VISIBLE int
94 lws_daemonize(const char *_lock_path)
95 {
96         struct sigaction act;
97         pid_t sid, parent;
98         int n, fd, ret;
99         char buf[10];
100
101         /* already a daemon */
102 //      if (getppid() == 1)
103 //              return 1;
104
105         fd = open(_lock_path, O_RDONLY);
106         if (fd >= 0) {
107                 n = read(fd, buf, sizeof(buf));
108                 close(fd);
109                 if (n) {
110                         n = atoi(buf);
111                         ret = kill(n, 0);
112                         if (ret >= 0) {
113                                 fprintf(stderr,
114                                      "Daemon already running from pid %d\n", n);
115                                 exit(1);
116                         }
117                         fprintf(stderr,
118                             "Removing stale lock file %s from dead pid %d\n",
119                                                                  _lock_path, n);
120                         unlink(lock_path);
121                 }
122         }
123
124         n = strlen(_lock_path) + 1;
125         lock_path = lws_malloc(n);
126         if (!lock_path) {
127                 fprintf(stderr, "Out of mem in lws_daemonize\n");
128                 return 1;
129         }
130         strcpy(lock_path, _lock_path);
131
132         /* Trap signals that we expect to receive */
133         signal(SIGCHLD, child_handler); /* died */
134         signal(SIGUSR1, child_handler); /* was happy */
135         signal(SIGALRM, child_handler); /* timeout daemonizing */
136
137         /* Fork off the parent process */
138         pid_daemon = fork();
139         if (pid_daemon < 0) {
140                 fprintf(stderr, "unable to fork daemon, code=%d (%s)",
141                     errno, strerror(errno));
142                 exit(9);
143         }
144
145         /* If we got a good PID, then we can exit the parent process. */
146         if (pid_daemon > 0) {
147
148                /*
149                 * Wait for confirmation signal from the child via
150                 * SIGCHILD / USR1, or for two seconds to elapse
151                 * (SIGALRM).  pause() should not return.
152                 */
153                alarm(2);
154
155                pause();
156                /* should not be reachable */
157                exit(1);
158        }
159
160         /* At this point we are executing as the child process */
161         parent = getppid();
162         pid_daemon = getpid();
163
164         /* Cancel certain signals */
165         signal(SIGCHLD, SIG_DFL); /* A child process dies */
166         signal(SIGTSTP, SIG_IGN); /* Various TTY signals */
167         signal(SIGTTOU, SIG_IGN);
168         signal(SIGTTIN, SIG_IGN);
169         signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */
170
171         /* Change the file mode mask */
172         umask(0);
173
174         /* Create a new SID for the child process */
175         sid = setsid();
176         if (sid < 0) {
177                 fprintf(stderr,
178                         "unable to create a new session, code %d (%s)",
179                         errno, strerror(errno));
180                 exit(2);
181         }
182
183         /*
184          * Change the current working directory.  This prevents the current
185          * directory from being locked; hence not being able to remove it.
186          */
187         if (chdir("/tmp") < 0) {
188                 fprintf(stderr,
189                         "unable to change directory to %s, code %d (%s)",
190                         "/", errno, strerror(errno));
191                 exit(3);
192         }
193
194         /* Redirect standard files to /dev/null */
195         if (!freopen("/dev/null", "r", stdin))
196                 fprintf(stderr, "unable to freopen() stdin, code %d (%s)",
197                                                        errno, strerror(errno));
198
199         if (!freopen("/dev/null", "w", stdout))
200                 fprintf(stderr, "unable to freopen() stdout, code %d (%s)",
201                                                        errno, strerror(errno));
202
203         if (!freopen("/dev/null", "w", stderr))
204                 fprintf(stderr, "unable to freopen() stderr, code %d (%s)",
205                                                        errno, strerror(errno));
206
207         /* Tell the parent process that we are A-okay */
208         kill(parent, SIGUSR1);
209
210         act.sa_handler = lws_daemon_closing;
211         sigemptyset(&act.sa_mask);
212         act.sa_flags = 0;
213
214         sigaction(SIGTERM, &act, NULL);
215
216         /* return to continue what is now "the daemon" */
217
218         return 0;
219 }
220