]> git.mdlowis.com Git - projs/tide.git/commitdiff
New daemonize() function to standardize creation of daemons
authorMichael D. Lowis <mike.lowis@gentex.com>
Mon, 7 Aug 2017 14:08:46 +0000 (10:08 -0400)
committerMichael D. Lowis <mike.lowis@gentex.com>
Mon, 7 Aug 2017 14:08:46 +0000 (10:08 -0400)
inc/edit.h
lib/utils.c
xcpd.c

index c8ab63f04b6074a71193cdbc70209f504e882432..fddd08bc1761251363368df7887ba60d63b78bc9 100644 (file)
@@ -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);
index ecf39ed01130b2319d04d67a32a5a8e0083d085d..30e7f3ef701f38675fc3ec573cc5a8aede7eb124 100644 (file)
@@ -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 e5e45accb4beab6b32256f2fee32f555c9d2e331..b1a27822e6a9a2b72cbd616d160c7600959a717e 100644 (file)
--- 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;
 }