coprocess question



The program below is from APUE.
It is about coprocess.
Mainly, the parent deliver input to ``add2" through pipe A, and the result is deliver back from ``add2" through pipe B.
The question is about stability, please search ``**" for it.

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>


#define MAXLINE 80


static void sig_pipe(int signo);

int main()
{
int n,fd1[2],fd2[2];
pid_t pid;
char line[MAXLINE];

if(signal(SIGPIPE,sig_pipe)==SIG_ERR){
perror("signal error");
exit(-1);
}

if(pipe(fd1)<0 || pipe(fd2)<0){
perror("pipe error");
exit(-1);
}

if((pid=fork())<0){
perror("fork error");
exit(-1);
}else if(pid>0){
close(fd1[0]);
close(fd2[1]);
while(fgets(line,MAXLINE,stdin)!=NULL){
n=strlen(line);
if(write(fd1[1],line,n)!=n){
perror("write error");
exit(-1);
}
//** Here is the question:
//Is it possible that the result is
//more than one digit, but only
//one digit is read from the pipe?
//For example:
//input is ``11 22\nC-d"
//will the output be "3"?
if((n=read(fd2[0],line,MAXLINE))<0){
perror("read error");
exit(-1);
}
if (n==0){
fprintf(stderr,"child closed pipe");
break;
}
}
line[n]=0;
if(fputs(line,stdout)==EOF){
perror("fputs error");
exit(-1);
}
exit(0);
} else {
close(fd1[1]);
close(fd2[0]);
if(fd1[0]!=STDIN_FILENO){
if(dup2(fd1[0],STDIN_FILENO)!=STDIN_FILENO){
perror("dup2 to STDIN_FILENO error");
exit(-1);
}
close(fd1[0]);
}
if(fd2[1]!=STDOUT_FILENO){
if(dup2(fd2[1],STDOUT_FILENO)!=STDOUT_FILENO){
perror("dup2 to STDOUT_FILENO error");
exit(-1);
}
close(fd2[1]);
}
if(execl("./add2","add2",(char*)0)<0){
perror("execl error");
exit(-1);
}
}
}

static void sig_pipe(int signo)
{
printf("SIGPIPE caught\n");
exit(1);
}
.



Relevant Pages