#include "config.h"
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#else
#ifdef HAVE_SYS_FCNTL_H
#include <sys/fcntl.h>
#endif
#endif
#include <sys/stat.h>
#if defined(HAVE_UNISTD_H)
#include <unistd.h>
#endif
#if defined(STDC_HEADERS)
#include <stdlib.h>
#endif
#if defined(QNX)
#include <unix.h>
#endif
#if !defined(HAVE_SETSID) && defined(SIGTSTP)
#if defined(HAVE_TERMIOS_H)
# include <termios.h>
#endif
#if !defined(TIOCNOTTY) && defined(HAVE_SGTTY_H)
# include <sgtty.h>
#endif
#endif
#if !defined(SIGCHLD) && defined(SIGCLD)
#define SIGCHLD SIGCLD
#endif
#include "fetchmail.h"
#include "tunable.h"
RETSIGTYPE
sigchld_handler (int sig)
{
extern volatile int lastsig;
pid_t pid;
#if defined(HAVE_WAITPID)
int status;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
continue;
#elif defined(HAVE_WAIT3)
#if defined(HAVE_UNION_WAIT) && !defined(__FreeBSD__)
union wait status;
#else
int status;
#endif
while ((pid = wait3(&status, WNOHANG, 0)) > 0)
continue;
#else
int status;
wait(&status);
#endif
lastsig = SIGCHLD;
}
int
daemonize (const char *logfile, void (*termhook)(int))
{
int fd;
pid_t childpid;
RETSIGTYPE sigchld_handler(int);
if (getppid() == 1)
goto nottyDetach;
#ifdef SIGTTOU
signal(SIGTTOU, SIG_IGN);
#endif
#ifdef SIGTTIN
signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTSTP
signal(SIGTSTP, SIG_IGN);
#endif
if ((childpid = fork()) < 0) {
report(stderr, "fork (%s)\n", strerror(errno));
return(PS_IOERR);
}
else if (childpid > 0)
exit(0);
#if defined(HAVE_SETSID)
if (setsid() < 0) {
report(stderr, "setsid (%s)\n", strerror(errno));
return(PS_IOERR);
}
#elif defined(SIGTSTP)
#ifndef __EMX__
setpgrp(0, getpid());
#endif
if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
ioctl(fd, TIOCNOTTY, (char *) 0);
close(fd);
}
#else
#ifndef __EMX__
setpgrp();
#endif
signal(SIGHUP, SIG_IGN);
if ((childpid = fork()) < 0) {
report(stderr, "fork (%)\n", strerror(errno));
return(PS_IOERR);
}
else if (childpid > 0) {
exit(0);
}
#endif
nottyDetach:
#if defined(HAVE_GETDTABLESIZE)
for (fd = getdtablesize()-1; fd >= 0; fd--)
#elif defined(NOFILE)
for (fd = NOFILE-1; fd >= 0; fd--)
#else
for (fd = 19; fd >= 0; fd--)
#endif
{
close(fd);
}
if ((fd = open("/dev/null", O_RDWR)) < 0) {
report(stderr, "open: /dev/null (%s)\n", strerror(errno));
return(PS_IOERR);
}
if (logfile)
fd = open(logfile, O_CREAT|O_WRONLY|O_APPEND, 0666);
else
if (dup(fd) < 0) {
report(stderr, "dup (%s)\n", strerror(errno));
return(PS_IOERR);
}
if (dup(fd) < 0) {
report(stderr, "dup (%s)\n", strerror(errno));
return(PS_IOERR);
}
chdir("/");
#if defined(DEF_UMASK)
umask(DEF_UMASK);
#else
umask(022);
#endif
signal(SIGCHLD, sigchld_handler);
#if defined(SIGPWR)
signal(SIGPWR, sigchld_handler);
#endif
return(0);
}