2 * daemon.c -- turn a process into a daemon under POSIX, SYSV, BSD.
4 * For license terms, see the file COPYING in this directory.
11 #include <sys/types.h>
15 #include <sys/fcntl.h> /* Solaris 2.5 requires this */
17 #if defined(HAVE_UNISTD_H)
21 #if defined(STDC_HEADERS)
29 /* BSD portability hack */
30 #if !defined(SIGCLD) && defined(SIGCHLD)
31 #define SIGCLD SIGCHLD
34 #include "fetchmail.h"
37 sigchld_handler (int sig)
38 /* process SIGCHLD/SIGCLD to obtain the exit code of the terminating process */
42 #if defined(HAVE_UNION_WAIT)
48 #if defined(HAVE_WAIT3)
49 while ((pid = wait3(&status, WNOHANG, (struct rusage *) 0)) > 0)
50 ; /* swallow 'em up. */
51 #elif defined(HAVE_WAITPID)
52 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
53 ; /* swallow 'em up. */
54 #else /* Zooks! Nothing to do but wait(), and hope we don't block... */
61 daemonize (const char *logfile, void (*termhook)(int))
62 /* detach from control TTY, become process group leader, catch SIGCHLD */
66 RETSIGTYPE sigchld_handler();
68 /* if we are started by init (process 1) via /etc/inittab we needn't
69 bother to detach from our process group context */
74 /* Ignore BSD terminal stop signals */
76 signal(SIGTTOU, SIG_IGN);
79 signal(SIGTTIN, SIG_IGN);
82 signal(SIGTSTP, SIG_IGN);
85 /* In case we were not started in the background, fork and let
86 the parent exit. Guarantees that the child is not a process
89 if ((childpid = fork()) < 0) {
93 else if (childpid > 0)
97 /* Make ourselves the leader of a new process group with no
98 controlling terminal */
100 #if defined(HAVE_SETSID) /* POSIX */
101 /* POSIX makes this soooo easy to do */
106 #elif defined(SIGTSTP) /* BSD */
107 /* change process group */
108 setpgrp(0, getpid());
110 /* lose controlling tty */
111 if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
112 ioctl(fd, TIOCNOTTY, (char *) 0);
115 #else /* SVR3 and older */
116 /* change process group */
119 /* lose controlling tty */
120 signal(SIGHUP, SIG_IGN);
121 if ((childpid = fork) < 0) {
125 else if (childpid > 0) {
126 exit(0); /* parent */
132 /* Close any/all open file descriptors */
133 #if defined(HAVE_GETDTABLESIZE)
134 for (fd = getdtablesize()-1; fd >= 0; fd--)
135 #elif defined(NOFILE)
136 for (fd = NOFILE-1; fd >= 0; fd--)
137 #else /* make an educated guess */
138 for (fd = 19; fd >= 0; fd--)
144 /* Reopen stdin descriptor on /dev/null */
145 if ((fd = open("/dev/null", O_RDWR)) < 0) { /* stdin */
146 perror("open: /dev/null");
151 fd = open(logfile, O_CREAT|O_WRONLY|O_APPEND, 0777); /* stdout */
153 if (dup(fd) < 0) { /* stdout */
157 if (dup(fd) < 0) { /* stderr */
162 /* move to root directory, so we don't prevent filesystem unmounts */
165 /* set our umask to something reasonable (we hope) */
166 #if defined(DEF_UMASK)
172 /* set up to catch child process termination signals */
173 signal(SIGCLD, sigchld_handler);
175 signal(SIGPWR, sigchld_handler);
181 /* daemon.c ends here */