From 12ce1683a5901ffa00b96f5805855e568a3c6054 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Thu, 31 Dec 2015 01:20:14 +0100 Subject: daemonise: add option to override pid file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mattias Andrée --- include/unistd.h | 9 +++++++++ src/unistd/daemonise.c | 5 +++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/include/unistd.h b/include/unistd.h index d95e08a..8479ae9 100644 --- a/include/unistd.h +++ b/include/unistd.h @@ -1081,6 +1081,14 @@ int daemon(int, int) */ #define DAEMONISE_KEEP_FDS 1024 +/** + * Override the PID file if it already exists, + * rather than failing. It is a bad idea to do + * this unless you already made sure that the + * daemon is not already running. + */ +#define DAEMONISE_NEW_PID 2048 + /** * Daemonise the process. This means to: * @@ -1163,6 +1171,7 @@ int daemon(int, int) * - `DAEMONISE_KEEP_STDIN` * - `DAEMONISE_KEEP_STDOUT` * - `DAEMONISE_KEEP_FDS` + * - `DAEMONISE_NEW_PID` * @param ... Enabled if `DAEMONISE_KEEP_FDS` is used, * do not add anything if `DAEMONISE_KEEP_FDS` * is unused. This is a `-1`-terminated list diff --git a/src/unistd/daemonise.c b/src/unistd/daemonise.c index f05e118..9df70da 100644 --- a/src/unistd/daemonise.c +++ b/src/unistd/daemonise.c @@ -161,6 +161,7 @@ static int dup_at_least_3(int old) * - `DAEMONISE_KEEP_STDIN` * - `DAEMONISE_KEEP_STDOUT` * - `DAEMONISE_KEEP_FDS` + * - `DAEMONISE_NEW_PID` * @param ... Enabled if `DAEMONISE_KEEP_FDS` is used, * do not add anything if `DAEMONISE_KEEP_FDS` * is unused. This is a `-1`-terminated list @@ -212,7 +213,7 @@ int daemonise(const char* name, int flags, ...) /* Validate flags. */ - if (flags & ~2047) + if (flags & (int)~(2048L * 2 - 1)) return errno = EINVAL, -1; if (flags & DAEMONISE_KEEP_STDERR) if (flags & DAEMONISE_CLOSE_STDERR) @@ -332,7 +333,7 @@ int daemonise(const char* name, int flags, ...) t (__pidfile == NULL); stpcpy(stpcpy(stpcpy(__pidfile, "/run/"), name), ".pid"); } - fd = open(__pidfile, O_WRONLY | O_CREAT | O_EXCL, 0644); + fd = open(__pidfile, O_WRONLY | O_CREAT | ((flags & DAEMONISE_NEW_PID) ? 0 : O_EXCL), 0644); if (fd == -1) { saved_errno = errno; -- cgit v1.2.3-70-g09d2