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