xref: /csrg-svn/lib/libc/gen/daemon.c (revision 59428)
143103Smarc /*-
243103Smarc  * Copyright (c) 1990 The Regents of the University of California.
343103Smarc  * All rights reserved.
443103Smarc  *
543103Smarc  * %sccs.include.redist.c%
643103Smarc  */
743103Smarc 
843103Smarc #if defined(LIBC_SCCS) && !defined(lint)
9*59428Sbostic static char sccsid[] = "@(#)daemon.c	5.5 (Berkeley) 04/27/93";
1043103Smarc #endif /* LIBC_SCCS and not lint */
1143103Smarc 
12*59428Sbostic #include <fcntl.h>
13*59428Sbostic #include <paths.h>
1445846Sbostic #include <unistd.h>
1543103Smarc 
16*59428Sbostic int
1744570Smarc daemon(nochdir, noclose)
1844570Smarc 	int nochdir, noclose;
1943103Smarc {
20*59428Sbostic 	int fd;
2143103Smarc 
22*59428Sbostic 	switch (fork()) {
23*59428Sbostic 	case -1:
2443103Smarc 		return (-1);
25*59428Sbostic 	case 0:
26*59428Sbostic 		break;
27*59428Sbostic 	default:
28*59428Sbostic 		_exit(0);
29*59428Sbostic 	}
30*59428Sbostic 
31*59428Sbostic 	if (setsid() == -1)
32*59428Sbostic 		return (-1);
33*59428Sbostic 
3444570Smarc 	if (!nochdir)
35*59428Sbostic 		(void)chdir("/");
3643103Smarc 
37*59428Sbostic 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
38*59428Sbostic 		(void)dup2(fd, STDIN_FILENO);
39*59428Sbostic 		(void)dup2(fd, STDOUT_FILENO);
40*59428Sbostic 		(void)dup2(fd, STDERR_FILENO);
41*59428Sbostic 		if (fd > 2)
42*59428Sbostic 			(void)close (fd);
4344570Smarc 	}
4450716Sbostic 	return (0);
4543103Smarc }
46