[cs631apue] Question about the chapter 15

Jan Schaumann jschauma at stevens.edu
Wed Oct 26 22:13:15 EDT 2016


bzhang41 <bzhang41 at stevens.edu> wrote:
 
> When the parent process call the 'popen', is there only one shell or two 
> shells ?

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[1] 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
concerned.)

> but line #44 seems to print the content in line to the pipe which is the 
> chid's 'shell'.

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
controlling terminal.

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.

-Jan


More information about the cs631apue mailing list