c - Can popen() make bidirectional pipes like pipe() + fork()? -
i'm implementing piping on simulated file system in c++ (with c). needs run commands in host shell perform piping on simulated file system.
i achieve pipe()
, fork()
, , system()
system calls, i'd prefer use popen()
(which handles creating pipe, forking process, , passing command shell). may not possible because (i think) need able write parent process of pipe, read on child process end, write output child, , read output parent. man page popen()
on system says bidirectional pipe possible, code needs run on system older version supporting unidirectional pipes.
with separate calls above, can open/close pipes achieve this. possible popen()
?
for trivial example, run ls -l | grep .txt | grep cmds
need to:
- open pipe , process run
ls -l
on host; read output back - pipe output of
ls -l
simulator - open pipe , process run
grep .txt
on host on piped output ofls -l
- pipe output of simulator (stuck here)
- open pipe , process run
grep cmds
on host on piped output ofgrep .txt
- pipe output of simulator , print it
man popen
from mac os x:
the
popen()
function 'opens' process creating bidirectional pipe, forking, , invoking shell. streams opened previouspopen()
calls in parent process closed in new child process. historically,popen()
implemented unidirectional pipe; hence, many implementations ofpopen()
allow mode argument specify reading or writing, not both. becausepopen()
implemented using bidirectional pipe, mode argument may request bidirectional data flow. mode argument pointer null-terminated string must 'r' reading, 'w' writing, or 'r+' reading , writing.
you seem have answered own question. if code needs work on older system doesn't support popen
opening bidirectional pipes, won't able use popen
(at least not 1 that's supplied).
the real question exact capabilities of older systems in question. in particular, pipe
support creating bidirectional pipes? if have pipe
can create bidirectional pipe, popen
doesn't, i'd write main stream of code use popen
bidirectional pipe, , supply implementation of popen
can use bidirectional pipe gets compiled in used needed.
if need support systems old enough pipe
supports unidirectional pipes, you're pretty stuck using pipe
, fork
, dup2
, etc., on own. i'd still wrap in function works almost modern version of popen
, instead of returning 1 file handle, fills in small structure 2 file handles, 1 child's stdin
, other child's stdout
.
Comments
Post a Comment