繁体   English   中英

Linux C fork-进程不停止

[英]Linux c fork - process dont stop

我正在尝试使用管道创建简单的程序。 不幸的是,程序没有像某些描述符未关闭那样正确结束。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>

int main(){
    int fd[2];
    pipe(fd);
    if(fork()==0){
        close(fd[0]);
        dup2(fd[1],1);
        close(fd[1]);
        execlp("ls", "ls", NULL);
    }
    else{
       if(fork() == 0){
           close(fd[1]);
           dup2(fd[0],0);
           close(fd[0]);
           execlp("tr", "tr", "a-z", "A-Z", NULL);
       }
   }
   return 0;
}

只要所有功能都成功(不过,您绝对应该在生产版本中进行错误检查),程序就可以正常工作。

但是,如果要等待两个孩子:

 wait(0); wait(0); //also skimping on the error checking
 //stuck
 return 0;

它会被卡住,因为tr会尝试读取其整个stdin (管道),并且只要父级仍然持有对写入端的引用,管道就无法结束。

 close(fd[1]);
 wait(0); wait(0); //also skimping on the error checking
 //stuck
 return 0;

它应该再次运行平稳。

该程序给人的印象是“没有结束”,因为这两个操作都是在分叉的过程中完成的,并且主过程在2个子代之前死掉,因此在打印结果之前将手交还给shell

return 0之前添加此行

     wait(NULL);

让主要过程等待所有孩子死后再解决。

请注意,您也无法再次分叉主进程(执行tr ),您将获得相同的结果。

else{
      close(fd[1]);
      dup2(fd[0],0);
      close(fd[0]);
      execlp("tr", "tr", "a-z", "A-Z", NULL);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM