2013-10-17 33 views
0

我正在写一个C程序,它运行多个管道的以下Linux命令:如何在Linux中使用C中的多个管道运行命令?

cat myfile1.txt | egrep Computing |厕所-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(”/斌/ egrep的”, “egrep的”, “计算”, NULL);“,在第二个孩子中用pid 2调用。

我不知道为什么我的程序挂在那里;是关于管道的僵局吗?

任何人都可以帮助我修改上述程序,以便它可以给我想要的结果吗?

+0

无用的'猫'奖励给你。你的表达应该是'egrep计算myfile1.txt | wc -l> myfile'开头。 –

回答

1

如何类似下面的伪代码:

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(); 

它更容易跟随,而不是循环使用像上面三个不同的块流。

大部分代码都可以放在通用函数中,例如为子进程设置描述符。

相关问题