ptg10805159
Section 15.4 Coprocesses 551
}
exit(0);
}
static void
sig_pipe(int signo)
{
printf("SIGPIPE caught\n");
exit(1);
}
Figure 15.18 Program to drive theadd2filter
Here, we create two pipes, with the parent and the child closing the ends they don’t
need. Wehave to use two pipes: one for the standardinput of the coprocess and one for
its standardoutput. The child then callsdup2to move the pipe descriptors onto its
standardinput and standardoutput, beforecallingexecl.
If we compile and run the program in Figure15.18, it works as expected.
Furthermore, if wekilltheadd2coprocess while the program in Figure15.18 is
waiting for our input and then enter two numbers, the signal handler is invoked when
the program writes to the pipe that has no reader.(See Exercise 15.4.)
Example
In the coprocessadd2(Figure15.17), we purposely used low-level I/O (UNIX system
calls):readandwrite.What happens if we rewrite this coprocess to use standard
I/O? Figure15.19 shows the new version.
#include "apue.h"
int
main(void)
{
int int1, int2;
char line[MAXLINE];
while (fgets(line, MAXLINE, stdin) != NULL) {
if (sscanf(line, "%d%d", &int1, &int2) == 2) {
if (printf("%d\n", int1 + int2) == EOF)
err_sys("printf error");
}else {
if (printf("invalid args\n") == EOF)
err_sys("printf error");
}
}
exit(0);
}
Figure 15.19 Filter to add two numbers, using standardI/O