[cs631apue] Question about the chapter 15
bzhang41 at stevens.edu
Wed Oct 26 22:40:41 EDT 2016
Thank you Prof.
The explaination is very helpful. I think I got it finnally.
bzhang41 <bzhang41 at stevens.edu> wrote:
When the parent process call the 'popen', is there only one shell or two
popen(3) creates a bi-directional pipe, forks, dup(2)'s the requested
file descriptors, and finally executes '/bin/sh -c <command>'.
Take the popen.c (on class website)for example,
line #38 seems to get the argv from the parent 'shell'
Yes, the program's argv is provided by the invoking shell, i.e. the
parent process of this program.
But it might be better to not think about what 'shells' are involved,
and instead think about what processes are. (The fact that popen(3)
invokes a shell is only relevant as far as command interpretation is
but line #44 seems to print the content in line to the pipe which is the
Line #44 prints data to the 'pipe' stream. This stream is what was
returned by the popen(3) call. Because we called popen(3) with "w" as
the second argument, the stream returned by popen(3) is dup(2)'d onto
the stdin of the process created by popen(3); the stdout of the process
created by popen(3) is unchanged, and so remains connected to the
As a result, any data printed to 'pipe' is fed into the command we gave
to popen(3) as the first argument; any output generated by that command
is printed to stdout (i.e. the terminal).
This is functionally the same as the code in pipe2.c, only by using
popen(3), we save ourselves a fair number of lines of code.
More information about the cs631apue