2 * damemon.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>
16 #if defined(HAVE_UNISTD_H)
20 #if defined(STDC_HEADERS)
28 /* BSD portability hack */
29 #if !defined(SIGCLD) && defined(SIGCHLD)
30 #define SIGCLD SIGCHLD
33 #include "fetchmail.h"
37 /* process SIGCHLD/SIGCLD to obtain the exit code of the terminating process */
41 #if defined(HAVE_UNION_WAIT)
47 #if defined(HAVE_WAIT3)
48 while ((pid = wait3(&status, WNOHANG, (struct rusage *) 0)) > 0)
49 ; /* swallow 'em up. */
50 #elif defined(HAVE_WAITPID)
51 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
52 ; /* swallow 'em up. */
53 #else /* Zooks! Nothing to do but wait(), and hope we don't block... */
60 daemonize (logfile, termhook)
61 /* detach from control TTY, become process group leader, catch SIGCHLD */
63 void (*termhook)(int);
67 RETSIGTYPE sigchld_handler();
69 /* if we are started by init (process 1) via /etc/inittab we needn't
70 bother to detach from our process group context */
75 /* Ignore BSD terminal stop signals */
77 signal(SIGTTOU, SIG_IGN);
80 signal(SIGTTIN, SIG_IGN);
83 signal(SIGTSTP, SIG_IGN);
86 /* In case we were not started in the background, fork and let
87 the parent exit. Guarantees that the child is not a process
90 if ((childpid = fork()) < 0) {
94 else if (childpid > 0)
98 /* Make ourselves the leader of a new process group with no
99 controlling terminal */
101 #if defined(HAVE_SETSID) /* POSIX */
102 /* POSIX makes this soooo easy to do */
107 #elif defined(SIGTSTP) /* BSD */
108 /* change process group */
109 setpgrp(0, getpid());
111 /* lose controlling tty */
112 if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
113 ioctl(fd, TIOCNOTTY, (char *) 0);
116 #else /* SVR3 and older */
117 /* change process group */
120 /* lose controlling tty */
121 signal(SIGHUP, SIG_IGN);
122 if ((childpid = fork) < 0) {
126 else if (childpid > 0) {
127 exit(0); /* parent */
133 /* Close any/all open file descriptors */
134 #if defined(HAVE_GETDTABLESIZE)
135 for (fd = getdtablesize()-1; fd >= 0; fd--)
136 #elif defined(NOFILE)
137 for (fd = NOFILE-1; fd >= 0; fd--)
138 #else /* make an educated guess */
139 for (fd = 19; fd >= 0; fd--)
145 /* Reopen stdin descriptor on /dev/null */
146 if ((fd = open("/dev/null", O_RDWR)) < 0) { /* stdin */
147 perror("open: /dev/null");
152 fd = open(logfile, O_CREAT|O_WRONLY|O_APPEND, 0777); /* stdout */
154 if (dup(fd) < 0) { /* stdout */
158 if (dup(fd) < 0) { /* stderr */
163 /* move to root directory, so we don't prevent filesystem unmounts */
166 /* set our umask to something reasonable (we hope) */
167 #if defined(DEF_UMASK)
173 /* set up to catch child process termination signals */
174 signal(SIGCLD, sigchld_handler);
176 signal(SIGPWR, sigchld_handler);
182 /* daemon.c ends here */