| 58 |
|
on the output of the parent. Make sure to call fflush(stdout) first |
| 59 |
|
if any data was buffered. It is illegal to set both PF_FILT_INP and |
| 60 |
|
PF_FILT_OUT, as a circular process is guaranteed to hang. |
| 61 |
+ |
|
| 62 |
+ |
If you want behavior similar to popen(cmd, "w") (again Unix-only), |
| 63 |
+ |
keeping stdout open in parent, use a duplicate descriptor like so: |
| 64 |
+ |
{ |
| 65 |
+ |
SUBPROC rtp = sp_inactive; |
| 66 |
+ |
FILE *fout; |
| 67 |
+ |
fflush(stdout); |
| 68 |
+ |
rtp.w = dup(fileno(stdout)); |
| 69 |
+ |
rtp.flags |= PF_FILT_OUT; |
| 70 |
+ |
if (open_process(&rtp, cmd_argv) <= 0) { |
| 71 |
+ |
perror(cmd_argv[0]); exit(1); |
| 72 |
+ |
} |
| 73 |
+ |
fout = fdopen(rtp.w, "w"); |
| 74 |
+ |
...write data to filter using fout until finished... |
| 75 |
+ |
fclose(fout); |
| 76 |
+ |
if (close_process(&rtp)) { |
| 77 |
+ |
perror(cmd_argv[0]); exit(1); |
| 78 |
+ |
} |
| 79 |
+ |
...can continue sending data directly to stdout... |
| 80 |
+ |
} |
| 81 |
+ |
We could also have called open_process() after fdopen() above, or after |
| 82 |
+ |
using fopen() on a file if we wanted to insert our filter before it. |
| 83 |
+ |
A similar sequence may be used to filter from stdin without closing |
| 84 |
+ |
it, though process termination becomes more difficult with two readers. |
| 85 |
+ |
Filtering input from a file works better, since the file is then read by |
| 86 |
+ |
the child only, as in: |
| 87 |
+ |
{ |
| 88 |
+ |
SUBPROC rtp = sp_inactive; |
| 89 |
+ |
FILE *fin = fopen(fname, "r"); |
| 90 |
+ |
if (fin == NULL) { |
| 91 |
+ |
open_error(fname); exit(1); |
| 92 |
+ |
} |
| 93 |
+ |
rtp.r = fileno(fin); |
| 94 |
+ |
rtp.flags |= PF_FILT_INP; |
| 95 |
+ |
if (open_process(&rtp, cmd_argv) <= 0) { |
| 96 |
+ |
perror(cmd_argv[0]); fclose(fin); exit(1); |
| 97 |
+ |
} |
| 98 |
+ |
...read filtered file data from fin until EOF... |
| 99 |
+ |
fclose(fin); |
| 100 |
+ |
if (close_process(&rtp)) { |
| 101 |
+ |
perror(cmd_argv[0]); exit(1); |
| 102 |
+ |
} |
| 103 |
+ |
} |
| 104 |
|
*/ |
| 105 |
|
|
| 106 |
|
|