From: Michael D. Lowis Date: Mon, 7 Aug 2017 14:08:46 +0000 (-0400) Subject: New daemonize() function to standardize creation of daemons X-Git-Url: https://git.mdlowis.com/?a=commitdiff_plain;h=d59afeff7bedb756589c8a2f31516f92ff2a29a1;p=projs%2Ftide.git New daemonize() function to standardize creation of daemons --- diff --git a/inc/edit.h b/inc/edit.h index c8ab63f..fddd08b 100644 --- a/inc/edit.h +++ b/inc/edit.h @@ -20,7 +20,10 @@ bool try_chdir(char* fpath); char* strconcat(char* dest, ...); bool file_exists(char* path); char* strmcat(char* first, ...); +int daemonize(void); +/* File Descriptor Event Handling + *****************************************************************************/ enum { INPUT, OUTPUT }; typedef void (*event_cbfn_t)(int fd, void* data); diff --git a/lib/utils.c b/lib/utils.c index ecf39ed..30e7f3e 100644 --- a/lib/utils.c +++ b/lib/utils.c @@ -165,3 +165,17 @@ char* strmcat(char* first, ...) { *curr = '\0'; return str; } + +int daemonize(void) { + pid_t pid; + if (chdir("/") < 0) return -1; + close(0), close(1), close(2); + pid = fork(); + if (pid < 0) return -1; + if (pid > 0) _exit(0); + if (setsid() < 0) return -1; + pid = fork(); + if (pid < 0) return -1; + if (pid > 0) _exit(0); + return 0; +} diff --git a/xcpd.c b/xcpd.c index e5e45ac..b1a2782 100644 --- a/xcpd.c +++ b/xcpd.c @@ -59,16 +59,10 @@ void serve_selection(void) { int main(int argc, char** argv) { SelText = fdgets(STDIN_FILENO); if (SelText) { - int pid = fork(); - if (pid == 0) { - close(STDIN_FILENO); - close(STDOUT_FILENO); - close(STDERR_FILENO); - chdir("/"); + if (daemonize() == 0) serve_selection(); - } else if (pid < 0) { - die("fork() failed"); - } + else + die("daemonize() failed"); } return 0; }