X-Git-Url: http://git.tuebingen.mpg.de/?p=dss.git;a=blobdiff_plain;f=daemon.c;h=0b201a8aa07b617e6eaea506cae4f096dc377e8a;hp=91a6ff26eebb9e6e070be6066d6a9e446c310c14;hb=2d10a72798da5489363088dfbe02ccbc5942cfcd;hpb=f33cf243ae1cb5657cccb7c43c99093936093b4a diff --git a/daemon.c b/daemon.c index 91a6ff2..0b201a8 100644 --- a/daemon.c +++ b/daemon.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 1997-2010 Andre Noll + * Copyright (C) 1997-2010 Andre Noll * * Licensed under the GPL v2. For licencing details see COPYING. */ @@ -31,24 +31,41 @@ * * \sa fork(2), setsid(2), dup(2). */ -void daemon_init(void) +int daemon_init(void) { pid_t pid; - int null; + int null, fd[2]; DSS_INFO_LOG(("daemonizing\n")); + if (pipe(fd) < 0) + goto err; pid = fork(); if (pid < 0) goto err; - if (pid) - exit(EXIT_SUCCESS); /* parent exits */ + if (pid) { + /* + * The parent process exits once it has received one byte from + * the reading end of the pipe. If the child exits before it + * was able to complete its setup (acquire the lock on the + * semaphore), the read() below will return zero. In this case + * we let the parent die unsuccessfully. + */ + char c; + int ret; + close(fd[1]); + ret = read(fd[0], &c, 1); + if (ret <= 0) { + DSS_EMERG_LOG(("child terminated unexpectedly\n")); + exit(EXIT_FAILURE); + } + exit(EXIT_SUCCESS); + } + close(fd[0]); /* become session leader */ if (setsid() < 0) goto err; - if (chdir("/") < 0) - goto err; umask(0); - null = open("/dev/null", O_RDONLY); + null = open("/dev/null", O_RDWR); if (null < 0) goto err; if (dup2(null, STDIN_FILENO) < 0) @@ -58,7 +75,7 @@ void daemon_init(void) if (dup2(null, STDERR_FILENO) < 0) goto err; close(null); - return; + return fd[1]; err: DSS_EMERG_LOG(("fatal: %s\n", strerror(errno))); exit(EXIT_FAILURE);