15
#define DAEMON_FD_MAX OPEN_MAX
16
#elif defined(_POSIX_OPEN_MAX)
17
#define DAEMON_FD_MAX _POSIX_OPEN_MAX
19
#define DAEMON_FD_MAX 0
22
#define OPEN_MAX_GUESS 256
24
static int fd_max (void)
27
int max = (int) sysconf(_SC_OPEN_MAX);
30
if (DAEMON_FD_MAX == 0) { /* indefinite limit */
36
debug(D_DEBUG, "sysconf(_SC_OPEN_MAX) error: %s", strerror(errno));
43
void daemonize (int cdroot)
45
/* Become seesion leader and lose controlling terminal */
48
debug(D_DEBUG, "could not fork: %s", strerror(errno));
51
exit(EXIT_SUCCESS); /* exit parent */
54
pid_t group = setsid();
55
if (group == (pid_t) -1) {
56
debug(D_DEBUG, "could not create session: %s", strerror(errno));
60
/* Second fork ensures process cannot acquire controlling terminal */
63
debug(D_DEBUG, "could not fork: %s", strerror(errno));
66
exit(EXIT_SUCCESS); /* exit parent */
70
int status = chdir("/");
72
debug(D_DEBUG, "could not chdir to `/': %s", strerror(errno));
79
int fd, max = fd_max();
80
for (fd = 0; fd < max; fd++) {
81
if (close(fd) == -1 && errno != EBADF) {
82
debug(D_DEBUG, "could not close open file descriptor: %s", strerror(errno));
87
int fd0 = open("/dev/null", O_RDONLY);
88
int fd1 = open("/dev/null", O_WRONLY);
89
int fd2 = open("/dev/null", O_WRONLY);
91
if (!(fd0 == STDIN_FILENO && fd1 == STDOUT_FILENO && fd2 == STDERR_FILENO)) {
92
debug(D_DEBUG, "could not open `/dev/null': %d %d %d: %s", fd0, fd1, fd2, strerror(errno));