UNIX管道子进程之间 [英] UNIX Pipes Between Child Processes

查看:184
本文介绍了UNIX管道子进程之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序,将产生子进程和管道之间,类似的命令行管道任意数量。就我而言,我试图做的ls -l命令|更多。并输出到标准输出,然后让父母继续执行多个命令

I'm trying to write a program that will spawn an arbitrary number of child processes and pipe between them, similar to a command line pipeline. In my case I'm trying to do "ls -l | more" and output that to stdout, then have the parent continue executing more commands.

我有以下的code作为一个小例子:

I have the following code as a minimal example:

int main (int argc, const char * argv[]) {
    int fd[2];
    pipe(fd); 
    chdir("/directory/with/lots/of/files");

    // Create one child process for more
    int pid = fork();
    if (pid == 0) {
        close(fd[1]);
        int ret = dup2(fd[0],0);
        if (ret < 0) perror("dup2");
        char *argv[10];
        argv[0] = "more";  argv[1] = NULL;
        execvp("more", argv);
    } 
    // Create another child process for ls
    int pid2 = fork();
    if (pid2 == 0) {
        int ret = dup2(fd[1],1);
        if (ret < 0) perror("dup2");
        char *argv[10];
        argv[0] = "ls";    argv[1] = "-l";   
        argv[2] = NULL;
        execvp("ls", argv);
    }

    // wait for the more process to finish
    int status;
    waitpid(pid, &status, 0);

    printf("Done!\n");
    return 0;
}

现在,当我执行程序(用当然是一个main()函数)我结了比较,预计。我会打D向下翻页更多的产出和u上去,似乎很好地工作。但是,当我到达的不是退出更喜欢做底,它只是留下一个空行。按Ctrl-C的工作,退出它,但它退出整个程序,这意味着DONE!线永远不会被打印出来。电影可以这里,说明发生了什么(请注意,在最后我preSS按Ctrl-C要回的bash)

Now, when I execute the program (enclosed in a main() function of course) what I end up with is more, which is expected. I'll hit "d" to page down more's output and "u" to go up, and it seems to work fine. But when I reach the bottom, instead of exiting like more does, it just leaves a blank line. Ctrl-C works to exit it but it exits the entire program, meaning the "Done!" line never gets printed. A movie is available here that illustrates what happens (note that at the very end I press Ctrl-C to get back to bash).

在这个有什么想法?我只是想弄清楚如何将其更改为,而不是经过到达底部,更多的退出并返回到父进程将一个空行,因此它可以继续执行。

Any thoughts on this? I'm just trying to figure out how to change it to where instead of going to a blank line after more reaches the bottom, more quits and returns to the parent process so it can continue executing.

推荐答案

您需要的close()至少你管的书写端,否则更多将永远不会看到EOF。例如:

You need to close() at least the writing end of your pipe, otherwise more will never see EOF. For example:

    ...

    // close parent's pipes
    close(fd[0]);
    close(fd[1]);

    // wait for the more process to finish
    int status;
    waitpid(pid, &status, 0);

    printf("Done!\n");
    return 0;
}

这篇关于UNIX管道子进程之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆