2013-07-15 184 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