diff options
Diffstat (limited to 'src/daemon.cc')
-rw-r--r-- | src/daemon.cc | 75 |
1 files changed, 38 insertions, 37 deletions
diff --git a/src/daemon.cc b/src/daemon.cc index f5ebe41..84ad8d9 100644 --- a/src/daemon.cc +++ b/src/daemon.cc @@ -45,7 +45,7 @@ Daemon::Daemon() Daemon::~Daemon() {} -int Daemon::run(const char *user, const char* group) +int Daemon::run(const char *user, const char* group, bool foreground) { int f; int fd; @@ -75,44 +75,45 @@ int Daemon::run(const char *user, const char* group) if(chdir("/") == -1) fprintf(stderr, "Could not chdir to '/'.\n"); umask(0); - f = fork(); - switch(f) { - case -1: // Fork error - perror("Fork in daemon.cc"); - return 1; - - case 0: // Forked child - // Switch to given group - if(setgid(gid) != 0) { - fprintf(stderr, "Failed to change to group \"%s\" (gid: %d), quitting.\n", group, gid); - perror(""); - fprintf(stderr, "Runnning daemon as current group\n"); - } - - // Switch to given user - if(setuid(uid) != 0) { - fprintf(stderr, "Failed to change to user \"%s\" (uid: %d), quitting.\n", user, uid); - perror(""); - fprintf(stderr, "Runnning daemon as current user\n"); + if(!foreground) { + f = fork(); + switch(f) { + case -1: // Fork error + perror("Fork in daemon.cc"); + return 1; + case 0: // Forked child + break; + default: // Parent + return 0; } - - // Redirect stdin, stdout and stderr to /dev/null - fd = open("/dev/null", O_NOCTTY | O_RDWR, 0666); + } - dup2(0, fd); - dup2(1, fd); - dup2(2, fd); + // Switch to given group + if(setgid(gid) != 0) { + fprintf(stderr, "Failed to change to group \"%s\" (gid: %d), quitting.\n", group, gid); + perror(""); + fprintf(stderr, "Runnning daemon as current group\n"); + } + + // Switch to given user + if(setuid(uid) != 0) { + fprintf(stderr, "Failed to change to user \"%s\" (uid: %d), quitting.\n", user, uid); + perror(""); + fprintf(stderr, "Runnning daemon as current user\n"); + } + + // Redirect stdin, stdout and stderr to /dev/null + fd = open("/dev/null", O_NOCTTY | O_RDWR, 0666); + + dup2(0, fd); + dup2(1, fd); + dup2(2, fd); - setsid(); - - signal (SIGTERM, SIG_IGN); - signal (SIGINT, SIG_IGN); - signal (SIGHUP, SIG_IGN); + setsid(); - return daemon_main(); - - default: // Parent - // exit(0); - return 0; - } + signal (SIGTERM, SIG_IGN); + if(!foreground) signal (SIGINT, SIG_IGN); + signal (SIGHUP, SIG_IGN); + + return daemon_main(); } |