aboutsummaryrefslogtreecommitdiffstats
path: root/sdk/proc/pdetach.c
diff options
context:
space:
mode:
authorWilliam Harrington <kb0iic@berzerkula.org>2025-01-14 16:06:02 -0600
committerWilliam Harrington <kb0iic@berzerkula.org>2025-01-14 16:06:02 -0600
commit0cc9b20c15460213e488bf5e70963b941482f628 (patch)
treebb0143245583ec846630f39bfa2258dba640ccd7 /sdk/proc/pdetach.c
parent0e084ade5069756d487b5c948c48b777e37c00c9 (diff)
Add source.
Diffstat (limited to 'sdk/proc/pdetach.c')
-rw-r--r--sdk/proc/pdetach.c78
1 files changed, 78 insertions, 0 deletions
diff --git a/sdk/proc/pdetach.c b/sdk/proc/pdetach.c
new file mode 100644
index 0000000..40814e4
--- /dev/null
+++ b/sdk/proc/pdetach.c
@@ -0,0 +1,78 @@
+/*
+ * Deamon-ify a user process; detach from controlling terminal and parent.
+ * $Id: daemon.c 1.2 Wed, 19 Mar 1997 12:44:53 -0500 dyfet $
+ * Copyright (c) 1997 by Tycho Softworks.
+ * For conditions on distribution and reuse see product license.
+ *
+ * Abstract:
+ * Daemon processes are commonly used in UNIX to build server
+ * applications. This module captures the essense of functionality
+ * required to make a process into a daemon within a single function
+ * call.
+ *
+ * Functions:
+ * daemon() - convert user process into a daemon.
+ */
+
+#include <proc/process.h>
+#include <std/signal.h>
+
+/* Daemonify a user process under UNIX.
+ *
+ * Abstract:
+ * In UNIX, a user process becomes a daemon by detaching itself from
+ * it's parent process and establishes it's own process group. A
+ * daemon may also detach itself from it's controlling terminal.
+ * This is usually accomplished through fork().
+ *
+ * Paramaters:
+ * flag - specifies daemon mode of operation:
+ * D_KEEPALL keeps all files open.
+ * D_KEEPSTDIO keeps stdio (stdin, stdout, stderr) open.
+ * D_KEEPNONIO detaches from stdio, keeps other files.
+ * D_KEEPNONE closes all open files.
+ *
+ * Returns:
+ * New pid of user process running as a daemon.
+ *
+ * Exceptions:
+ * Any failure terminates the process. No error message is possible
+ * since the process may already be detached from user I/O.
+ */
+
+pid_t pdetach(int flag)
+{
+ pid_t pid;
+ int max = OPEN_MAX;
+ int i;
+
+ signal(SIGHUP, SIG_IGN);
+
+ i = 0;
+ if(flag == D_KEEPSTDIO)
+ i = 3;
+
+ if(flag == D_KEEPNONIO)
+ max = 3;
+
+ while((i < max) && (flag != D_KEEPALL))
+ close(i++);
+
+ pid = fork();
+ if(pid < 0)
+ return pid;
+
+ if(pid > 0)
+ exit(EX_OK);
+
+ setsid();
+ setpgid(0, getpid());
+ pid = fork();
+ if(pid < 0)
+ return pid;
+
+ if(pid > 0)
+ exit(EX_OK);
+
+ return getpid();
+}