]> git.sur5r.net Git - openldap/blob - libraries/liblutil/detach.c
5d27febf9c525e1a114bd54f16d3d0174eb90a60
[openldap] / libraries / liblutil / 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 "portable.h"
14
15 #include <stdio.h>
16
17 #include <ac/signal.h>
18 #include <ac/unistd.h>
19
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <sys/file.h>
23 #include <sys/ioctl.h>
24
25 #include "lutil.h"
26
27 void
28 lutil_detach( int debug, int do_close )
29 {
30         int             i, sd, nbits;
31
32 #ifdef HAVE_SYSCONF
33         nbits = sysconf( _SC_OPEN_MAX );
34 #elif HAVE_GETDTABLESIZE
35         nbits = getdtablesize();
36 #else
37         nbits = FD_SETSIZE;
38 #endif
39
40 #ifdef FD_SETSIZE
41         if ( nbits > FD_SETSIZE ) {
42                 nbits = FD_SETSIZE;
43         }
44 #endif /* FD_SETSIZE */
45
46         if ( debug == 0 ) {
47                 for ( i = 0; i < 5; i++ ) {
48 #if HAVE_THR
49                         switch ( fork1() )
50 #else
51                         switch ( fork() )
52 #endif
53                         {
54                         case -1:
55                                 sleep( 5 );
56                                 continue;
57
58                         case 0:
59                                 break;
60
61                         default:
62                                 _exit( 0 );
63                         }
64                         break;
65                 }
66
67                 if ( do_close )
68                         for ( i = 3; i < nbits; i++ )
69                                 close( i );
70
71                 (void) chdir( "/" );
72
73                 if ( (sd = open( "/dev/null", O_RDWR )) == -1 ) {
74                         perror( "/dev/null" );
75                         exit( 1 );
76                 }
77                 for ( i = 0;  i < 3;  i++ )
78                         if ( sd != i && isatty( i ) )
79                                 (void) dup2( sd, i );
80                 if ( sd > 2 )
81                         close( sd );
82
83 #ifdef HAVE_SETSID
84                 (void) setsid();
85 #else /* HAVE_SETSID */
86                 if ( (sd = open( "/dev/tty", O_RDWR )) != -1 ) {
87                         (void) ioctl( sd, TIOCNOTTY, NULL );
88                         (void) close( sd );
89                 }
90 #endif /* HAVE_SETSID */
91         } 
92
93         (void) SIGNAL( SIGPIPE, SIG_IGN );
94 }