X-Git-Url: http://git.tuebingen.mpg.de/?p=dss.git;a=blobdiff_plain;f=daemon.c;h=709785b437041654e3cacd2fd4f252aea8fa4173;hp=d48e30c995245986bc0761eda9e7ecf52c0736e0;hb=56f81b0dfa62bb5bf2c338733d9370a8b11bfc39;hpb=69add8d2b5d6c8f402e9f94d47df732479535f2d diff --git a/daemon.c b/daemon.c index d48e30c..709785b 100644 --- a/daemon.c +++ b/daemon.c @@ -1,8 +1,4 @@ -/* - * Copyright (C) 1997-2010 Andre Noll - * - * Licensed under the GPL v2. For licencing details see COPYING. - */ +/* SPDX-License-Identifier: GPL-2.0 */ /** \file daemon.c Some helpers for programs that detach from the console. */ @@ -19,9 +15,10 @@ #include #include "gcc-compat.h" -#include "error.h" +#include "err.h" #include "log.h" -#include "string.h" +#include "str.h" +#include "daemon.h" /** * Do the usual stuff to become a daemon. @@ -30,24 +27,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"); + 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) @@ -57,9 +71,9 @@ 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)); + DSS_EMERG_LOG(("fatal: %s\n", strerror(errno))); exit(EXIT_FAILURE); } @@ -77,8 +91,8 @@ FILE *open_log(const char *logfile_name) assert(logfile_name); logfile = fopen(logfile_name, "a"); if (!logfile) { - DSS_EMERG_LOG("can not open %s: %s\n", logfile_name, - strerror(errno)); + DSS_EMERG_LOG(("can not open %s: %s\n", logfile_name, + strerror(errno))); exit(EXIT_FAILURE); } setlinebuf(logfile); @@ -96,7 +110,7 @@ void close_log(FILE* logfile) { if (!logfile) return; - DSS_INFO_LOG("closing logfile\n"); + DSS_INFO_LOG(("closing logfile\n")); fclose(logfile); } @@ -105,6 +119,6 @@ void close_log(FILE* logfile) */ void log_welcome(int loglevel) { - DSS_INFO_LOG("***** welcome to dss ******\n"); - DSS_DEBUG_LOG("using loglevel %d\n", loglevel); + DSS_INFO_LOG(("***** welcome to dss ******\n")); + DSS_DEBUG_LOG(("using loglevel %d\n", loglevel)); }