xref: /csrg-svn/lib/libc/gen/daemon.c (revision 61111)
143103Smarc /*-
2*61111Sbostic  * Copyright (c) 1990, 1993
3*61111Sbostic  *	The Regents of the University of California.  All rights reserved.
443103Smarc  *
543103Smarc  * %sccs.include.redist.c%
643103Smarc  */
743103Smarc 
843103Smarc #if defined(LIBC_SCCS) && !defined(lint)
9*61111Sbostic static char sccsid[] = "@(#)daemon.c	8.1 (Berkeley) 06/04/93";
1043103Smarc #endif /* LIBC_SCCS and not lint */
1143103Smarc 
1259428Sbostic #include <fcntl.h>
1359428Sbostic #include <paths.h>
1445846Sbostic #include <unistd.h>
1543103Smarc 
1659428Sbostic int
daemon(nochdir,noclose)1744570Smarc daemon(nochdir, noclose)
1844570Smarc 	int nochdir, noclose;
1943103Smarc {
2059428Sbostic 	int fd;
2143103Smarc 
2259428Sbostic 	switch (fork()) {
2359428Sbostic 	case -1:
2443103Smarc 		return (-1);
2559428Sbostic 	case 0:
2659428Sbostic 		break;
2759428Sbostic 	default:
2859428Sbostic 		_exit(0);
2959428Sbostic 	}
3059428Sbostic 
3159428Sbostic 	if (setsid() == -1)
3259428Sbostic 		return (-1);
3359428Sbostic 
3444570Smarc 	if (!nochdir)
3559428Sbostic 		(void)chdir("/");
3643103Smarc 
3759428Sbostic 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
3859428Sbostic 		(void)dup2(fd, STDIN_FILENO);
3959428Sbostic 		(void)dup2(fd, STDOUT_FILENO);
4059428Sbostic 		(void)dup2(fd, STDERR_FILENO);
4159428Sbostic 		if (fd > 2)
4259428Sbostic 			(void)close (fd);
4344570Smarc 	}
4450716Sbostic 	return (0);
4543103Smarc }
46