1 /*- 2 * Copyright (c) 1990 The Regents of the University of California. 3 * All rights reserved. 4 * 5 * %sccs.include.redist.c% 6 */ 7 8 #if defined(LIBC_SCCS) && !defined(lint) 9 static char sccsid[] = "@(#)daemon.c 5.5 (Berkeley) 04/27/93"; 10 #endif /* LIBC_SCCS and not lint */ 11 12 #include <fcntl.h> 13 #include <paths.h> 14 #include <unistd.h> 15 16 int 17 daemon(nochdir, noclose) 18 int nochdir, noclose; 19 { 20 int fd; 21 22 switch (fork()) { 23 case -1: 24 return (-1); 25 case 0: 26 break; 27 default: 28 _exit(0); 29 } 30 31 if (setsid() == -1) 32 return (-1); 33 34 if (!nochdir) 35 (void)chdir("/"); 36 37 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { 38 (void)dup2(fd, STDIN_FILENO); 39 (void)dup2(fd, STDOUT_FILENO); 40 (void)dup2(fd, STDERR_FILENO); 41 if (fd > 2) 42 (void)close (fd); 43 } 44 return (0); 45 } 46