daemonize.c 5.3 KB

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