]> git.sur5r.net Git - openldap/blob - servers/slapd/back-shell/fork.c
Update for Alpha3 from -devel as of OPENLDAP_DEVEL_981116.
[openldap] / servers / slapd / back-shell / fork.c
1 /* fork.c - fork and exec a process, connecting stdin/out w/pipes */
2
3 #include "portable.h"
4
5 #include <stdio.h>
6
7 #include <ac/string.h>
8 #include <ac/socket.h>
9 #include <ac/unistd.h>
10
11 #include "slap.h"
12 #include "shell.h"
13
14 int
15 forkandexec(
16     char        **args,
17     FILE        **rfp,
18     FILE        **wfp
19 )
20 {
21         int     p2c[2], c2p[2];
22         int     pid;
23
24         if ( pipe( p2c ) != 0 || pipe( c2p ) != 0 ) {
25                 Debug( LDAP_DEBUG_ANY, "pipe failed\n", 0, 0, 0 );
26                 return( -1 );
27         }
28
29         /*
30          * what we're trying to set up looks like this:
31          *      parent *wfp -> p2c[1] | p2c[0] -> stdin child
32          *      parent *rfp <- c2p[0] | c2p[1] <- stdout child
33          */
34
35         switch ( (pid = fork()) ) {
36         case 0:         /* child */
37                 close( p2c[1] );
38                 close( c2p[0] );
39                 if ( dup2( p2c[0], 0 ) == -1 || dup2( c2p[1], 1 ) == -1 ) {
40                         Debug( LDAP_DEBUG_ANY, "dup2 failed\n", 0, 0, 0 );
41                         exit( -1 );
42                 }
43
44                 execv( args[0], args );
45
46                 Debug( LDAP_DEBUG_ANY, "execv failed\n", 0, 0, 0 );
47                 exit( -1 );
48
49         case -1:        /* trouble */
50                 Debug( LDAP_DEBUG_ANY, "fork failed\n", 0, 0, 0 );
51                 return( -1 );
52
53         default:        /* parent */
54                 close( p2c[0] );
55                 close( c2p[1] );
56                 break;
57         }
58
59         if ( (*rfp = fdopen( c2p[0], "r" )) == NULL || (*wfp = fdopen( p2c[1],
60             "w" )) == NULL ) {
61                 Debug( LDAP_DEBUG_ANY, "fdopen failed\n", 0, 0, 0 );
62                 close( c2p[0] );
63                 close( p2c[1] );
64
65                 return( -1 );
66         }
67
68         return( pid );
69 }