繁体   English   中英

如何在C中使用多个管道在Linux中运行命令?

[英]How to run a command in Linux with multiple pipes in C?

我正在编写一个C程序,它通过多个管道运行以下Linux命令:

猫myfile1.txt | egrep计算| wc -l> myfile

我的代码如下:

    int p_fd[2];
    pid_t childpid, waitReturn;
    int pid=1;
    int status, i;

    pipe(p_fd);

    for( i = 1 ; i < 3 ; i++ )
        if( childpid = fork() )
            break;
        else
            pid++;

    while( childpid != ( waitReturn = wait( &status ) ) )
        if( ( waitReturn == -1 ) && ( errno != EINTR ) )
            break;

    if ( childpid > 0 && pid == 1 ){
        printf("%d\n", pid);
        int fd;
        if ( ( fd= open("myfile", O_CREAT|O_RDWR|O_TRUNC, 00644)) == -1 )
        {
                printf("Error: Cannot open file in open()\n");
                exit(1);
        }
        close(0);
        dup(p_fd[0]);
        close(1);
        dup(fd);
        close(p_fd[0]);
        close(p_fd[1]);
        close(fd);
        execl("/bin/wc", "wc", "-l", NULL);
    }else if( childpid > 0 && pid == 2 ){
        printf("%d\n", pid);
        close(0);
        dup(p_fd[0]);
        close(1);
        dup(p_fd[1]);
        close(p_fd[0]);
        close(p_fd[1]);

        execl("/bin/egrep", "egrep", "Computing", NULL);

    }else if( childpid == 0 && pid == 3 ){
        printf("%d\n", pid);
        close(1);
        dup(p_fd[1]);
        close(p_fd[0]);
        close(p_fd[1]);

        execl("/bin/cat", "cat", "myfile1.txt", NULL);
    }   

    return 0;

但是,我的程序在到达“ execl(“ / bin / egrep”,“ egrep”,“ Computing”,NULL);“时挂起,在第二个子进程中使用pid 2调用它。

我不知道我的程序挂在那里的原因。 这与管道的僵局有关吗?

谁能帮助我修改上面的程序,使其达到预期的效果?

下面的伪代码怎么样:

create_pipe_between_cat_and_egrep();
create_pipe_between_egrep_and_wc();
create_destination_file();

if (fork() == 0)
{
    /* Process for cat */
    setup_pipe_stdout_for_cat();
    execl("cat", "cat", "arguments");
}

if (fork() == 0)
{
    /* process for egrep */
    setup_pipe_stdin_stdout_for_egrep();
    execl("egrep", "egrep", "arguments");
}

if (fork() == 0)
{
    /* process for wc */
    setup_pipe_stdin_for_wc();
    setup_file_stdout_for_wc();
    execl("wc", "wc", "arguments");
}

wait_for_all_three_child_processes_to_finish();

用上面的三个不同的块而不是循环来遵循流程是很容易的。

许多代码可以放入通用函数中,例如为子进程设置stdin / stdout描述符。

暂无
暂无

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

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