From 66e9a0322ba241a375ddb145ff468454b2baf715 Mon Sep 17 00:00:00 2001 From: deva Date: Wed, 7 Jul 2010 12:25:13 +0000 Subject: Refuse to start if pid file already exists, or cannot be written. Remove pid file when shutting down (if possible). --- server/src/daemon.cc | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/server/src/daemon.cc b/server/src/daemon.cc index 9de3807..aabaa2f 100644 --- a/server/src/daemon.cc +++ b/server/src/daemon.cc @@ -103,8 +103,19 @@ int Daemon::run(const char *user, const char* group, bool detach, umask(0); + if(pidfile != "" ) { + FILE *fp = fopen(pidfile.c_str(), "r"); + if(fp != NULL) { + fclose(fp); + fprintf(stderr, "Could not write pid file \"%s\"" + " - file already exists.\n", + pidfile.c_str()); + return -1; + } + } + if(detach) { - if( daemon(0, 0) == -1) { + if(daemon(0, 0) == -1) { perror(""); return -1; } @@ -112,10 +123,12 @@ int Daemon::run(const char *user, const char* group, bool detach, if(pidfile != "" ) { pid_t pid = getpid(); + FILE *fp = fopen(pidfile.c_str(), "w"); - if(errno) { + if(fp == NULL) { fprintf(stderr, "Could not write pid file \"%s\"", pidfile.c_str()); perror(""); + return -1; } else { fprintf(fp, "%lu", (unsigned long int)pid); fclose(fp); @@ -151,5 +164,11 @@ int Daemon::run(const char *user, const char* group, bool detach, // Don't disable Ctrl+c when running in foreground. //if(detach) signal (SIGINT, SIG_IGN); - return daemon_main(); + int ret = daemon_main(); + + if(pidfile != "") { + unlink(pidfile.c_str()); + } + + return ret; } -- cgit v1.2.3