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>
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"
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 (logfile, termhook)
62 /* detach from control TTY, become process group leader, catch SIGCHLD */
64 void (*termhook)(int);
68 RETSIGTYPE sigchld_handler();
70 /* if we are started by init (process 1) via /etc/inittab we needn't
71 bother to detach from our process group context */
76 /* Ignore BSD terminal stop signals */
78 signal(SIGTTOU, SIG_IGN);
81 signal(SIGTTIN, SIG_IGN);
84 signal(SIGTSTP, SIG_IGN);
87 /* In case we were not started in the background, fork and let
88 the parent exit. Guarantees that the child is not a process
91 if ((childpid = fork()) < 0) {
95 else if (childpid > 0)
99 /* Make ourselves the leader of a new process group with no
100 controlling terminal */
102 #if defined(HAVE_SETSID) /* POSIX */
103 /* POSIX makes this soooo easy to do */
108 #elif defined(SIGTSTP) /* BSD */
109 /* change process group */
110 setpgrp(0, getpid());
112 /* lose controlling tty */
113 if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
114 ioctl(fd, TIOCNOTTY, (char *) 0);
117 #else /* SVR3 and older */
118 /* change process group */
121 /* lose controlling tty */
122 signal(SIGHUP, SIG_IGN);
123 if ((childpid = fork) < 0) {
127 else if (childpid > 0) {
128 exit(0); /* parent */
134 /* Close any/all open file descriptors */
135 #if defined(HAVE_GETDTABLESIZE)
136 for (fd = getdtablesize()-1; fd >= 0; fd--)
137 #elif defined(NOFILE)
138 for (fd = NOFILE-1; fd >= 0; fd--)
139 #else /* make an educated guess */
140 for (fd = 19; fd >= 0; fd--)
146 /* Reopen stdin descriptor on /dev/null */
147 if ((fd = open("/dev/null", O_RDWR)) < 0) { /* stdin */
148 perror("open: /dev/null");
153 fd = open(logfile, O_CREAT|O_WRONLY|O_APPEND, 0777); /* stdout */
155 if (dup(fd) < 0) { /* stdout */
159 if (dup(fd) < 0) { /* stderr */
164 /* move to root directory, so we don't prevent filesystem unmounts */
167 /* set our umask to something reasonable (we hope) */
168 #if defined(DEF_UMASK)
174 /* set up to catch child process termination signals */
175 signal(SIGCLD, sigchld_handler);
177 signal(SIGPWR, sigchld_handler);
183 /* daemon.c ends here */