1 /* detach.c -- routines to daemonize a process */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2016 The OpenLDAP Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted only as authorized by the OpenLDAP
12 * A copy of this license is available in the file LICENSE in the
13 * top-level directory of the distribution or, alternatively, at
14 * <http://www.OpenLDAP.org/license.html>.
17 * Copyright (c) 1990, 1994 Regents of the University of Michigan.
18 * All rights reserved.
20 * Redistribution and use in source and binary forms are permitted
21 * provided that this notice is preserved and that due credit is given
22 * to the University of Michigan at Ann Arbor. The name of the University
23 * may not be used to endorse or promote products derived from this
24 * software without specific prior written permission. This software
25 * is provided ``as is'' without express or implied warranty.
27 /* This work was originally developed by the University of Michigan
28 * and distributed as part of U-MICH LDAP.
35 #include <ac/stdlib.h>
36 #include <ac/signal.h>
37 #include <ac/socket.h>
38 #include <ac/unistd.h>
43 #ifdef HAVE_SYS_FILE_H
46 #ifdef HAVE_SYS_IOCTL_H
47 #include <sys/ioctl.h>
53 lutil_detach( int debug, int do_close )
55 int i, sd, nbits, pid;
58 nbits = sysconf( _SC_OPEN_MAX );
59 #elif defined(HAVE_GETDTABLESIZE)
60 nbits = getdtablesize();
66 if ( nbits > FD_SETSIZE ) {
69 #endif /* FD_SETSIZE */
72 for ( i = 0; i < 5; i++ ) {
93 if ( (sd = open( "/dev/null", O_RDWR )) == -1 &&
94 (sd = open( "/dev/null", O_RDONLY )) == -1 &&
95 /* Panic -- open *something* */
96 (sd = open( "/", O_RDONLY )) == -1 ) {
99 /* redirect stdin, stdout, stderr to /dev/null */
100 dup2( sd, STDIN_FILENO );
101 dup2( sd, STDOUT_FILENO );
102 dup2( sd, STDERR_FILENO );
115 /* close everything else */
116 for ( i = 0; i < nbits; i++ ) {
117 if( i != STDIN_FILENO &&
118 i != STDOUT_FILENO &&
132 #elif defined(TIOCNOTTY)
133 if ( (sd = open( "/dev/tty", O_RDWR )) != -1 ) {
134 (void) ioctl( sd, TIOCNOTTY, NULL );
141 (void) SIGNAL( SIGPIPE, SIG_IGN );