2013-07-15 185 views
0

到目前为止,我有一个函数execute_command(command_t),可以执行简单的命令,如“ls -l”,“cat test.txt”等。但是,当我尝试实现管道,它不会产生任何东西。这里的代码:管道之间的2子进程不产生任何输出

int thePipe[2]; 
pid_t child = fork(); 
int status1=0; 
pipe(thePipe); 
if(child==(pid_t)-1){ 
    fprintf(stderr, "error when fork the process\n"); 
} else if(child==0){ 
    close one pipe and make duplicate 
    execute command[0] 
} else{ 
    waitpid(child, &status1, 0); 
} 
int status2=0; 
pid_t child2 = fork(); 
pipe(thePipe); 
if(child2==(pid_t)-1){ 
    fprintf(stderr, "error when fork the process\n"); 
} else if(child2==0){ 
    close one pipe and make duplicate 
    execute command[1]; 
} else { 
    waitpid(child2, &status2, 0); 
} 

如果输入命令是:

cat test.txt | grep aaa 

命令 “猫的test.txt” 将被存储在 “C-> u.command [0]” 和命令“ grep aaa“将存储在”c-> u.command [1]“中。

我做错了什么?谢谢

+0

这是因为你叉使用管道功能的前 – Alexis

回答

2

你想创建一个你的两个孩子之间的管道。也就是说,拨打pipe()一次然后让两个孩子都使用它。你调用它两次,用新的管道覆盖原来的管道。基本上,保持对事物的布局/订单,你想:

create pipe 
fork() 
if child { 
    close read end of pipe 
    send stdout to write end of pipe 
    exec command[0] 
} 
fork() 
if child { 
    close write end of pipe 
    set stdin to read end of pipe 
    exec command[1] 
} 
close read and write ends of pipe 
wait for children to finish