ptg10805159
542 Interprocess Communication Chapter 15
parent cmdstring(child)
fp stdin
Figure 15.10Result offp = popen(cmdstring,"w")
One way to remember the final argument topopenis to remember that, likefopen,the
returned file pointer is readable iftypeis"r"or writable iftypeis"w".
Thepclosefunction closes the standardI/O stream, waits for the command to
terminate, and returns the termination status of the shell. (Wedescribed the
termination status in Section 8.6. Thesystemfunction, described in Section 8.13, also
returns the termination status.) If the shell cannot be executed, the termination status
returned bypcloseis as if the shell had executedexit(127).
Thecmdstringis executed by the Bourne shell, as in
sh -ccmdstring
This means that the shell expands any of its special characters incmdstring.This allows
us to say,for example,
fp = popen("ls *.c", "r");
or
fp = popen("cmd 2>&1", "r");
Example
Let’s redo the program from Figure15.6, usingpopen.This is shown in Figure15.11.
#include "apue.h"
#include <sys/wait.h>
#define PAGER "${PAGER:-more}" /* environment variable, or default */
int
main(int argc, char *argv[])
{
char line[MAXLINE];
FILE *fpin, *fpout;
if (argc != 2)
err_quit("usage: a.out <pathname>");
if ((fpin = fopen(argv[1], "r")) == NULL)
err_sys("can’t open %s", argv[1]);
if ((fpout = popen(PAGER, "w")) == NULL)
err_sys("popen error");
/* copy argv[1] to pager */