| •1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
#include <unistd.h> |
| 20 |
#include <stdlib.h> |
| 21 |
#include <sys/wait.h> |
| 22 |
|
| 23 |
#include "popenRWE.h" |
| 24 |
|
| 25 |
int popenRWE(int *rwepipe, const char *path) { |
| 26 |
int in[2]; |
| 27 |
int out[2]; |
| 28 |
int err[2]; |
| 29 |
int pid; |
| 30 |
int rc; |
| 31 |
const char *argv[4] = {"sh", "-c", NULL, NULL}; |
| 32 |
argv[2] = path; |
| 33 |
|
| 34 |
rc = pipe(in); |
| 35 |
if (rc<0) |
| 36 |
goto error_in; |
| 37 |
|
| 38 |
rc = pipe(out); |
| 39 |
if (rc<0) |
| 40 |
goto error_out; |
| 41 |
|
| 42 |
rc = pipe(err); |
| 43 |
if (rc<0) |
| 44 |
goto error_err; |
| 45 |
|
| 46 |
pid = fork(); |
| 47 |
if (pid > 0) { |
| 48 |
close(in[0]); |
| 49 |
close(out[1]); |
| 50 |
close(err[1]); |
| 51 |
rwepipe[0] = in[1]; |
| 52 |
rwepipe[1] = out[0]; |
| 53 |
rwepipe[2] = err[0]; |
| 54 |
return pid; |
| 55 |
} else if (pid == 0) { |
| 56 |
close(in[1]); |
| 57 |
close(out[0]); |
| 58 |
close(err[0]); |
| 59 |
close(0); |
| •60 |
if(dup(in[0]) < 0) exit(2); |
| 61 |
close(1); |
| •62 |
if(dup(out[1]) < 0) exit(2); |
| 63 |
close(2); |
| •64 |
if(dup(err[1]) < 0) exit(2); |
| 65 |
|
| 66 |
execvp(argv[0], (char**)argv); |
| 67 |
exit(1); |
| 68 |
} else |
| 69 |
goto error_fork; |
| 70 |
|
| 71 |
return pid; |
| 72 |
|
| 73 |
error_fork: |
| 74 |
close(err[0]); |
| 75 |
close(err[1]); |
| 76 |
error_err: |
| 77 |
close(out[0]); |
| 78 |
close(out[1]); |
| 79 |
error_out: |
| 80 |
close(in[0]); |
| 81 |
close(in[1]); |
| 82 |
error_in: |
| 83 |
return -1; |
| 84 |
} |
| 85 |
|
| 86 |
int pcloseRWE(int pid, int *rwepipe) { |
| 87 |
int rc, status; |
| 88 |
close(rwepipe[0]); |
| 89 |
close(rwepipe[1]); |
| 90 |
close(rwepipe[2]); |
| •91 |
do { |
| 92 |
rc = waitpid(pid, &status, 0); |
| 93 |
} while (rc != 0 && ! WIFEXITED(status)); |
| 94 |
return status; |
| 95 |
} |