From 0cc9b20c15460213e488bf5e70963b941482f628 Mon Sep 17 00:00:00 2001 From: William Harrington Date: Tue, 14 Jan 2025 16:06:02 -0600 Subject: Add source. --- sdk/proc/pdetach.c | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 sdk/proc/pdetach.c (limited to 'sdk/proc/pdetach.c') 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 +#include + +/* 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(); +} -- cgit v1.2.3-54-g00ecf