X-Git-Url: http://git.ozlabs.org/?a=blobdiff_plain;f=ccan%2Fdaemonize%2Fdaemonize.c;h=bd32ecbbaeebc866426eb212ca3811264e060d21;hb=f6557ca6537bc4d37fb4be215184a632533ba4e7;hp=ca4aafc8fa99c403b8396dd0d871d3840e536e46;hpb=cd13fd53487ba6f10b78ab1ffd625cb3da7ab22a;p=ccan diff --git a/ccan/daemonize/daemonize.c b/ccan/daemonize/daemonize.c index ca4aafc8..bd32ecbb 100644 --- a/ccan/daemonize/daemonize.c +++ b/ccan/daemonize/daemonize.c @@ -1,8 +1,10 @@ +/* Licensed under BSD-MIT - see LICENSE file for details */ #include #include #include #include #include +#include /* This code is based on Stevens Advanced Programming in the UNIX * Environment. */ @@ -13,16 +15,26 @@ bool daemonize(void) /* Separate from our parent via fork, so init inherits us. */ if ((pid = fork()) < 0) return false; + /* use _exit() to avoid triggering atexit() processing */ if (pid != 0) - exit(0); + _exit(0); /* Don't hold files open. */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); + /* 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) + return false; + if (dup2(0, STDERR_FILENO) != STDERR_FILENO) + return false; + close(0); + /* Session leader so ^C doesn't whack us. */ - setsid(); + if (setsid() == (pid_t)-1) + return false; /* Move off any mount points we might be in. */ if (chdir("/") != 0) return false;