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