|
代码中父进程不是应该在执行到if (childpid) break才跳出循环吗?为什么在执行完if((childpid=fork())==-1)这一句就跳出并输出错误
PS:代码的功能是用一个进程环来计算Fibonacci数列
代码如下:
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(read(fd[0],buf,MAXSIZE)==-1)
perror("Failed to read from the pipe"); |
|