]> git.sur5r.net Git - openldap/blob - servers/ldapd/detach.c
Resync with HEAD
[openldap] / servers / ldapd / detach.c
1 /*
2  * Copyright (c) 1990, 1994 Regents of the University of Michigan.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that this notice is preserved and that due credit is given
7  * to the University of Michigan at Ann Arbor. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific prior written permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  */
12
13 #include <stdio.h>
14 #include <sys/types.h>
15 #ifdef SVR4
16 #include <sys/stat.h>
17 #endif /* svr4 */
18 #include <fcntl.h>
19 #include <sys/file.h>
20 #include <sys/ioctl.h>
21 #include <signal.h>
22 #include "portable.h"
23
24 #ifdef USE_SYSCONF
25 #include <unistd.h>
26 #endif /* USE_SYSCONF */
27
28
29 detach()
30 {
31         int             i, sd, nbits;
32 #ifdef LDAP_DEBUG
33         extern int      ldap_debug;
34 #endif
35
36 #ifdef USE_SYSCONF
37         nbits = sysconf( _SC_OPEN_MAX );
38 #else /* USE_SYSCONF */
39         nbits = getdtablesize();
40 #endif /* USE_SYSCONF */
41
42 #ifdef LDAP_DEBUG
43         if ( ldap_debug == 0 ) {
44 #endif
45                 for ( i = 0; i < 5; i++ ) {
46                         switch ( fork() ) {
47                         case -1:
48                                 sleep( 5 );
49                                 continue;
50
51                         case 0:
52                                 break;
53
54                         default:
55                                 _exit( 0 );
56                         }
57                         break;
58                 }
59
60                 for ( i = 3; i < nbits; i++ )
61                         close( i );
62
63                 (void) chdir( "/" );
64
65                 if ( (sd = open( "/dev/null", O_RDWR )) == -1 ) {
66                         perror( "/dev/null" );
67                         exit( 1 );
68                 }
69                 if ( isatty( 0 ) )
70                         (void) dup2( sd, 0 );
71                 if ( isatty( 1 ) )
72                         (void) dup2( sd, 1 );
73                 if ( isatty(2) )
74                         (void) dup2( sd, 2 );
75                 close( sd );
76
77 #ifdef USE_SETSID
78                 setsid();
79 #else /* USE_SETSID */
80                 if ( (sd = open( "/dev/tty", O_RDWR )) != -1 ) {
81                         (void) ioctl( sd, TIOCNOTTY, NULL );
82                         (void) close( sd );
83                 }
84 #endif /* USE_SETSID */
85 #ifdef LDAP_DEBUG
86         } 
87 #endif
88
89         (void) signal( SIGPIPE, SIG_IGN );
90 }