The Linux Programming Interface

(nextflipdebug5) #1

902 Chapter 44


When we run the program in Listing 44-4, we see the following:

$ ./pipe_ls_wc
24
$ ls | wc -l Verify the results using shell commands
24

44.5 Talking to a Shell Command via a Pipe: popen()


A common use for pipes is to execute a shell command and either read its output
or send it some input. The popen() and pclose() functions are provided to simplify
this task.

The popen() function creates a pipe, and then forks a child process that execs a
shell, which in turn creates a child process to execute the string given in command.
The mode argument is a string that determines whether the calling process will read
from the pipe (mode is r) or write to it (mode is w). (Since pipes are unidirectional,
two-way communication with the executed command is not possible.) The value of
mode determines whether the standard output of the executed command is con-
nected to the write end of the pipe or its standard input is connected to the read
end of the pipe, as shown in Figure 44-4.

Figure 44-4: Overview of process relationships and pipe usage for popen()

On success, popen() returns a file stream pointer that can be used with the stdio
library functions. If an error occurs (e.g., mode is not r or w, pipe creation fails, or
the fork() to create the child fails), then popen() returns NULL and sets errno to indi-
cate the cause of the error.
After the popen() call, the calling process uses the pipe to read the output of
command or to send input to it. Just as with pipes created using pipe(), when reading
from the pipe, the calling process encounters end-of-file once command has closed

#include <stdio.h>

FILE *popen(const char *command, const char *mode);
Returns file stream, or NULL on error
int pclose(FILE *stream);
Returns termination status of child process, or –1 on error

fp

a) modeis r

stdout

fork(),
exec()

fork(),
exec()

pipe
fp

b) modeis w

stdin

fork(),
exec()

fork(),
exec()

pipe

calling
process

command

/bin/sh

calling
process

command

/bin/sh
Free download pdf