2 * Copyright (C) 1997-2010 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file daemon.c Some helpers for programs that detach from the console. */
13 #include <sys/types.h>
21 #include "gcc-compat.h"
28 * Do the usual stuff to become a daemon.
30 * Fork, become session leader, dup fd 0, 1, 2 to /dev/null.
32 * \sa fork(2), setsid(2), dup(2).
39 DSS_INFO_LOG(("daemonizing\n"));
47 * The parent process exits once it has received one byte from
48 * the reading end of the pipe. If the child exits before it
49 * was able to complete its setup (acquire the lock on the
50 * semaphore), the read() below will return zero. In this case
51 * we let the parent die unsuccessfully.
56 ret = read(fd[0], &c, 1);
58 DSS_EMERG_LOG(("child terminated unexpectedly\n"));
64 /* become session leader */
68 null = open("/dev/null", O_RDWR);
71 if (dup2(null, STDIN_FILENO) < 0)
73 if (dup2(null, STDOUT_FILENO) < 0)
75 if (dup2(null, STDERR_FILENO) < 0)
80 DSS_EMERG_LOG(("fatal: %s\n", strerror(errno)));
85 * fopen() the given file in append mode.
87 * \param logfile_name The name of the file to open.
89 * \return Either calls exit() or returns a valid file handle.
91 FILE *open_log(const char *logfile_name)
96 logfile = fopen(logfile_name, "a");
98 DSS_EMERG_LOG(("can not open %s: %s\n", logfile_name,
107 * Close the log file of the daemon.
109 * \param logfile The log file handle.
111 * It's OK to call this with logfile == \p NULL.
113 void close_log(FILE* logfile)
117 DSS_INFO_LOG(("closing logfile\n"));
122 * Log the startup message.
124 void log_welcome(int loglevel)
126 DSS_INFO_LOG(("***** welcome to dss ******\n"));
127 DSS_DEBUG_LOG(("using loglevel %d\n", loglevel));