diff --git a/ccan/daemonize/daemonize.c b/ccan/daemonize/daemonize.c index 3c0a53a8b..5cc338540 100644 --- a/ccan/daemonize/daemonize.c +++ b/ccan/daemonize/daemonize.c @@ -10,6 +10,8 @@ * Environment. */ bool daemonize(void) { + const char *dev_null = "/dev/null"; + int fd; pid_t pid; /* Separate from our parent via fork, so init inherits us. */ @@ -25,11 +27,21 @@ bool daemonize(void) /* Many routines write to stderr; that can cause chaos if used * for something else, so set it here. */ - if (open("/dev/null", O_WRONLY) != 0) + /* reopen STDIN */ + if ((fd = open(dev_null, O_RDONLY)) == -1) return false; - if (dup2(0, STDERR_FILENO) != STDERR_FILENO) - return false; - close(0); + if (dup2(fd, STDIN_FILENO) != STDIN_FILENO) + return false; + if (fd > STDERR_FILENO) close(fd); + /* reopen STDOUT */ + if ((fd = open(dev_null, O_WRONLY)) == -1) + return false; + if (dup2(fd, STDOUT_FILENO) != STDOUT_FILENO) + return false; + /* reopen STDERR */ + if (dup2(fd, STDERR_FILENO) != STDERR_FILENO) + return false; + if (fd > STDERR_FILENO) close(fd); /* Session leader so ^C doesn't whack us. */ setsid(); diff --git a/ccan/daemonize/test/run.c b/ccan/daemonize/test/run.c index 73f021118..207719363 100644 --- a/ccan/daemonize/test/run.c +++ b/ccan/daemonize/test/run.c @@ -68,8 +68,8 @@ int main(int argc, char *argv[]) ok1(daemonized.ppid == 1); #endif ok1(daemonized.in_root_dir); - ok1(daemonized.read_from_stdin == EBADF); - ok1(daemonized.write_to_stdout == EBADF); + ok1(daemonized.read_from_stdin == 0); + ok1(daemonized.write_to_stdout == 0); ok1(daemonized.write_to_stderr == 0); return exit_status();