summaryrefslogtreecommitdiff
path: root/lib/daemon.c
blob: c3106b5096a909a6207939312a59581931ad908e (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
/*
 * daemon.c - "daemonize" a process
 */

#include "config.h"

int daemon(int nochdir, int noclose)
{
	int nullfd;
	pid_t f;
	
	if (!nochdir) {
		if (chdir("/"))
			return -1;
	}

	if (!noclose) {
		if ((nullfd = open("/dev/null", O_RDWR)) < 0 ||
		    dup2(nullfd, 0) < 0 ||
		    dup2(nullfd, 1) < 0 ||
		    dup2(nullfd, 2) < 0)
			return -1;
		close(nullfd);
	}

	f = fork();
	if (f < 0)
		return -1;
	else if (f > 0)
		_exit(0);

#ifdef HAVE_SETSID
	return setsid();
#else
	return 0;
#endif
}