LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 653|回复: 1

为什么父进程会在这里跳出?

[复制链接]
发表于 2009-12-1 10:13:46 | 显示全部楼层 |阅读模式
代码中父进程不是应该在执行到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");
发表于 2009-12-1 11:24:41 | 显示全部楼层
fork 返回 -1 会设置 errno,你把 errno 打出来看看。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表