/* * 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(); }