Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 15.4 Coprocesses 549


parent child (coprocess)
fd1[1]

fd2[0]

stdin

stdout

pipe1

pipe2

Figure 15.16Driving a coprocess by writing its standardinput and reading its standardoutput

The program in Figure15.17 is a simple coprocess that reads two numbers from its
standardinput, computes their sum, and writes the sum to its standardoutput.
(Coprocesses usually do moreinteresting work than we illustrate here. This example is
admittedly contrived so that we can study the plumbing needed to connect the
processes.)
#include "apue.h"

int
main(void)
{
int n, int1, int2;
char line[MAXLINE];

while ((n = read(STDIN_FILENO, line, MAXLINE)) > 0) {
line[n] = 0; /* null terminate */
if (sscanf(line, "%d%d", &int1, &int2) == 2) {
sprintf(line, "%d\n", int1 + int2);
n=strlen(line);
if (write(STDOUT_FILENO, line, n) != n)
err_sys("write error");
}else {
if (write(STDOUT_FILENO, "invalid args\n", 13) != 13)
err_sys("write error");
}
}
exit(0);
}

Figure 15.17 Simple filter to add two numbers

We compile this program and leave the executable in the fileadd2.
The program in Figure15.18 invokes theadd2coprocess after reading two numbers
from its standardinput. The value from the coprocess is written to its standardoutput.
#include "apue.h"

static void sig_pipe(int); /* our signal handler */

int
Free download pdf