|
为了实现计算Fibonacci数列 初始读入的数据为1 1
父进程将计算出的结果写入管道 子进程读取管道中的数据在进行运算 如此往复 直到n个进程结束
程序到 if((childpid=fork())==-1)会输出Failed to read from the pipe: Bad file descriptor
Failed to write to the pipe: Bad file descriptorFailed to read from the pipe: Bad file descriptor
Failed to write to the pipe: Bad file descriptorFailed to read from the pipe: Bad file descriptor
不知道为什么到这一句就会从循环跳出?
恳请大家帮助!!
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#define MAXSIZE 4
int main(int argc, char *argv[]) {
pid_t childpid;
int error;
int fd[2];
int i,num1,num2;
int nprocs;
char buf[]="1 1";
char newbuf[MAXSIZE],s[MAXSIZE];
if ((argc!=2)||((nprocs=atoi(argv[1]))<=0)) {
fprintf(stderr,"Usage: %s \n",argv[0]);
return 1;
}
if (pipe(fd)==-1) {
perror("Failed to create pipeline!");
return 1;
}
if ((dup2(fd[0],STDIN_FILENO)==-1)||(dup2(fd[1],STDOUT_FILENO)==-1)) {
perror("Failed to connect pipe!");
return 1;
}
if ((close(fd[0])==-1)||(close(fd[1])==-1)) {
perror("Failed to close extra descriptor!");
return 1;
}
for (i=1;i<nprocs;i++) {
if (pipe(fd)==-1) {
fprintf(stderr,"[%ld]:failed to create pipe %d: %s\n", (long)getpid(),i,strerror(errno));
return 1;
}
if((childpid=fork())==-1) {
fprintf(stderr,"[%ld]:failed to creat child %d: %s\n",(long)getpid(),i,strerror(errno));
return 1;
}
if(childpid>0)
error=dup2(fd[1],STDOUT_FILENO);
else
error=dup2(fd[0],STDIN_FILENO);
if(error==-1) {
fprintf(stderr,"[%ld]: failed to dup pipes for iterations %d: %s \n",(long)getpid(),i,strerror(errno));
return 1;
}
if(close(fd[0])==-1 || close(fd[1])==-1 ) {
fprintf(stderr,"[%ld]: failed to close the extra descriptor %d: %s \n",(long) getpid(),i,strerror(errno));
return 1;
}
if (childpid)
break;
}
if (i!=1)
if(read(fd[0],buf,MAXSIZE)==-1)
perror("Failed to read from the pipe");
num1=atoi(&buf[0]);
num2=atoi(&buf[2]);
num1=num1+num2;
sprintf(s,"%d",num1);
sprintf(newbuf,"%d %d", num2,num1);
if(write(fd[1],newbuf,MAXSIZE)==-1) {
fprintf(stderr,"Failed to write to the pipe: %s",strerror(errno));
return 1;
}
fprintf(stderr,"The squence is: %s", newbuf);
return 0;
} |
|