首页 > 解决方案 > 为什么等待后我不能关闭管道?

问题描述

我试图了解如何wait()工作。ls -F -1 | nl这是在命令行中模仿的ac程序

    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
    }

我最初认为的顺序wait(NULL)并不close(fd)重要。但显然确实如此。wait(NULL)为什么这段代码在正常工作的情况下移动两个下面的代码时一直运行而不打印任何东西close(fd[1])

标签: cprocess

解决方案


nl在 EOF on 之前不会退出stdin。在父子 1 都关闭管道的写入端之前,这不会发生。子 1 在退出时会执行此操作,父级会在退出时执行此操作close(fd[1])

所以你陷入了僵局。在第二个返回之前您不会关闭 FD wait(),但在您关闭 FD 之前它不会返回。


推荐阅读