diff options
author | deva <deva> | 2010-07-07 12:25:13 +0000 |
---|---|---|
committer | deva <deva> | 2010-07-07 12:25:13 +0000 |
commit | 66e9a0322ba241a375ddb145ff468454b2baf715 (patch) | |
tree | fed56f45ea81deb04d2431c3885940f174ee236d | |
parent | 78cab4908b1784c67bee0064502854b1a984342f (diff) |
Refuse to start if pid file already exists, or cannot be written. Remove pid file when shutting down (if possible).
-rw-r--r-- | server/src/daemon.cc | 25 |
1 files 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; } |