chiark / gitweb /
debugging for thing that crashed
[inn-innduct.git] / lib / daemonize.c
1 /*  $Id: daemonize.c 6395 2003-07-12 19:13:49Z rra $
2 **
3 **  Become a long-running daemon.
4 **
5 **  Usage:
6 **
7 **      daemonize(path);
8 **
9 **  Performs all of the various system-specific stuff required to become a
10 **  long-running daemon.  Also chdir to the provided path (which is where
11 **  core dumps will go on most systems).
12 */
13
14 #include "config.h"
15 #include "clibrary.h"
16 #include <fcntl.h>
17 #include <sys/ioctl.h>
18 #include <sys/stat.h>
19
20 #include "inn/messages.h"
21 #include "libinn.h"
22
23 void
24 daemonize(const char *path)
25 {
26     int status;
27     int fd;
28
29     /* Fork and exit in the parent to disassociate from the current process
30        group and become the leader of a new process group. */
31     status = fork();
32     if (status < 0)
33         sysdie("cant fork");
34     else if (status > 0)
35         _exit(0);
36
37     /* setsid() should take care of disassociating from the controlling
38        terminal, and FreeBSD at least doesn't like TIOCNOTTY if you don't
39        already have a controlling terminal.  So only use the older TIOCNOTTY
40        method if setsid() isn't available. */
41 #if HAVE_SETSID
42     if (setsid() < 0)
43         syswarn("cant become session leader");
44 #elif defined(TIOCNOTTY)
45     fd = open("/dev/tty", O_RDWR);
46     if (fd >= 0) {
47         if (ioctl(fd, TIOCNOTTY, NULL) < 0)
48             syswarn("cant disassociate from the terminal");
49         close(fd);
50     }
51 #endif /* defined(TIOCNOTTY) */
52
53     if (chdir(path) < 0)
54         syswarn("cant chdir to %s", path);
55
56     fd = open("/dev/null", O_RDWR, 0);
57     if (fd != -1) {
58         dup2(fd, STDIN_FILENO);
59         dup2(fd, STDOUT_FILENO);
60         dup2(fd, STDERR_FILENO);
61         if (fd > 2)
62             close(fd);
63     }
64 }