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>
16 #if defined(HAVE_SYS_WAIT_H)
17 # include <sys/wait.h>
20 #if defined(HAVE_UNISTD_H)
24 #if defined(STDC_HEADERS)
32 /* BSD portability hack */
33 #if !defined(SIGCLD) && defined(SIGCHLD)
34 #define SIGCLD SIGCHLD
37 #include "fetchmail.h"
41 /* process SIGCHLD/SIGCLD to obtain the exit code of the terminating process */
45 #if defined(HAVE_UNION_WAIT)
51 #if defined(HAVE_WAIT3)
52 while ((pid = wait3(&status, WNOHANG, (struct rusage *) 0)) > 0)
53 ; /* swallow 'em up. */
54 #elif defined(HAVE_WAITPID)
55 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
56 ; /* swallow 'em up. */
57 #else /* Zooks! Nothing to do but wait(), and hope we don't block... */
64 daemonize (logfile, termhook)
65 /* detach from control TTY, become process group leader, catch SIGCHLD */
67 void (*termhook)(int);
71 RETSIGTYPE sigchld_handler();
73 /* if we are started by init (process 1) via /etc/inittab we needn't
74 bother to detach from our process group context */
79 /* Ignore BSD terminal stop signals */
81 signal(SIGTTOU, SIG_IGN);
84 signal(SIGTTIN, SIG_IGN);
87 signal(SIGTSTP, SIG_IGN);
90 /* In case we were not started in the background, fork and let
91 the parent exit. Guarantees that the child is not a process
94 if ((childpid = fork()) < 0) {
98 else if (childpid > 0)
102 /* Make ourselves the leader of a new process group with no
103 controlling terminal */
105 #if defined(HAVE_SETSID) /* POSIX */
106 /* POSIX makes this soooo easy to do */
111 #elif defined(SIGTSTP) /* BSD */
112 /* change process group */
113 setpgrp(0, getpid());
115 /* lose controlling tty */
116 if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
117 ioctl(fd, TIOCNOTTY, (char *) 0);
120 #else /* SVR3 and older */
121 /* change process group */
124 /* lose controlling tty */
125 signal(SIGHUP, SIG_IGN);
126 if ((childpid = fork) < 0) {
130 else if (childpid > 0) {
131 exit(0); /* parent */
137 /* Close any/all open file descriptors */
138 #if defined(HAVE_GETDTABLESIZE)
139 for (fd = getdtablesize()-1; fd >= 0; fd--)
140 #elif defined(NOFILE)
141 for (fd = NOFILE-1; fd >= 0; fd--)
142 #else /* make an educated guess */
143 for (fd = 19; fd >= 0; fd--)
149 /* Reopen stdin descriptor on /dev/null */
150 if ((fd = open("/dev/null", O_RDWR)) < 0) { /* stdin */
151 perror("open: /dev/null");
156 fd = open(logfile, O_CREAT|O_WRONLY|O_APPEND, 0777); /* stdout */
158 if (dup(fd) < 0) { /* stdout */
162 if (dup(fd) < 0) { /* stderr */
167 /* move to root directory, so we don't prevent filesystem unmounts */
170 /* set our umask to something reasonable (we hope) */
171 #if defined(DEF_UMASK)
177 /* set up to catch child process termination signals */
178 signal(SIGCLD, sigchld_handler);
180 signal(SIGPWR, sigchld_handler);
186 /* daemon.c ends here */