簡體   English   中英

2個子進程之間的管道不產生任何輸出

[英]pipe between 2 child process do not produce any output

到目前為止,我得到了一個函數execute_command(command_t),可以執行簡單的命令,如“ls -l”,“cat test.txt”等。但是,當我嘗試實現管道時,它不會產生任何東西。 這是代碼:

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

命令“cat test.txt”將存儲在“c-> u.command [0]”中,命令“grep aaa”將存儲在“c-> u.command [1]”中。

我做錯什么了嗎? 謝謝

您想在兩個孩子之間創建一個管道。 也就是說,調用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM