aboutsummaryrefslogtreecommitdiffstats
path: root/sdk/proc/pdetach.c
blob: 40814e4756d9500ed7f82b95a200108d1065b8d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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();
}