简体   繁体   English

为什么等待后我不能关闭管道?

[英]Why can't I close pipes after wait?

I am trying to understand how wait() works.我试图了解wait()是如何工作的。 This is the a c program that mimics ls -F -1 | nl这是一个模仿ls -F -1 | nl的 c 程序ls -F -1 | nl in command line命令行中的ls -F -1 | nl

    pipe(fd); // create the pipe

    pid1 = fork(); //fork child 1

    if (pid1 == 0) // child 1
    {
        close(fd[0]);                       // close read end of the pipe
        dup2(fd[1], 1);                     // child 1 redirects stdout to write to the pipe
        execlp("ls", "bin/ls", "-F", NULL); // execute ls -F
        close(fd[1]);                       // close write end of the pipe
    }

    pid2 = fork(); //fork child 2

    if (pid2 == 0) // child 2
    {
        close(fd[1]);                  // close write end of the pipe
        dup2(fd[0], 0);                // child 2 redirects stdin to read from the pipe
        execlp("nl", "usr/bin", NULL); // execute nl
        close(fd[0]);                  // close read end of the pipe
    }

    if (pid1 != 0 && pid2 != 0) // parent process
    {
        wait(NULL);   // wait for a child
        wait(NULL);   // wait for another child
        close(fd[0]); // close read end of parent pipe
        close(fd[1]); // close write end of parent pipe
    }

I initially thought the order of wait(NULL) and close(fd) doesn't matter.我最初认为wait(NULL)close(fd)的顺序无关紧要。 But apparently does.但显然确实如此。 Why this code keeps running without printing anything while moving the two wait(NULL) below the close(fd[1]) works fine?为什么在将两个wait(NULL)移到close(fd[1])下方时,此代码继续运行而不打印任何内容?

nl won't exit until it gets EOF on stdin . nlstdin上获得 EOF 之前不会退出。 This won't happen until both the parent and child 1 close the write end of the pipe.在父子 1 都关闭 pipe 的写入端之前,这不会发生。 Child 1 will do this when it exits, the parent does this when it does close(fd[1]) .子 1 在退出时会执行此操作,父级会在close(fd[1])

So you've got a deadlock.所以你陷入了僵局。 You won't close the FD until the second wait() returns, but it won't return until you close the FD.在第二个wait()返回之前,您不会关闭 FD,但在您关闭 FD 之前它不会返回。

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

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