Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

548 Interprocess Communication Chapter 15


if ((fpin = popen("myuclc", "r")) == NULL)
err_sys("popen error");
for ( ; ; ) {
fputs("prompt> ", stdout);
fflush(stdout);
if (fgets(line, MAXLINE, fpin) == NULL) /* read from pipe */
break;
if (fputs(line, stdout) == EOF)
err_sys("fputs error to pipe");
}
if (pclose(fpin) == -1)
err_sys("pclose error");
putchar(’\n’);
exit(0);
}

Figure 15.15 Invoke uppercase/lowercase filter to read commands

We need to callfflushafter writing the prompt, because the standardoutput is
normally line buffered, and the prompt does not contain a newline.

15.4 Coprocesses


AUNIX system filter is a program that reads from standardinput and writes to
standardoutput. Filters arenormally connected linearly in shell pipelines. Afilter
becomes acoprocesswhen the same program generates the filter’s input and reads the
filter ’s output.
The Korn shell provides coprocesses[Bolsky and Korn 1995].The Bourne shell, the
Bourne-again shell, and the C shell don’t provide a way to connect processes together as
coprocesses. A coprocess normally runs in the background from a shell, and its
standardinput and standardoutput areconnected to another program using a pipe.
Although the shell syntax required to initiate a coprocess and connect its input and
output to other processes is quite contorted (see pp. 62–63 of Bolsky and Korn[ 1995 ]for
all the details), coprocesses arealso useful from a C program.
Whereaspopengives us a one-way pipe to the standardinput or from the standard
output of another process, with a coprocess we have two one-way pipes to the other
process: one to its standardinput and one from its standardoutput. Wewant to write
to its standardinput, let it operate on the data, and then read from its standardoutput.

Example


Let’s look at coprocesses with an example. The process creates two pipes: one is the
standardinput of the coprocess and the other is the standardoutput of the coprocess.
Figure15.16 shows this arrangement.
Free download pdf