2 * damemon.c -- turn a process into a daemon under POSIX, SYSV, BSD.
4 * For license terms, see the file COPYING in this directory.
10 #include <sys/types.h>
15 #if defined(HAVE_SYS_WAIT_H)
16 # include <sys/wait.h>
19 #if defined(HAVE_UNISTD_H)
27 /* BSD portability hack */
28 #if !defined(SIGCLD) && defined(SIGCHLD)
29 #define SIGCLD SIGCHLD
32 #include "fetchmail.h"
36 /* process SIGCHLD/SIGCLD to obtain the exit code of the terminating process */
40 #if defined(HAVE_UNION_WAIT)
46 #if defined(HAVE_WAIT3)
47 while ((pid = wait3(&status, WNOHANG, (struct rusage *) 0)) > 0)
48 ; /* swallow 'em up. */
49 #elif defined(HAVE_WAITPID)
50 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
51 ; /* swallow 'em up. */
52 #else /* Zooks! Nothing to do but wait(), and hope we don't block... */
59 daemonize (logfile, termhook)
60 /* detach from control TTY, become process group leader, catch SIGCHLD */
62 void (*termhook)(int);
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);
179 /* daemon.c ends here */