2011-10-20 82 views
3

我不太確定如何在兩個子進程之間創建管道。這是我做的方式:在C UNIX shell中管道

pipe(&fd[0]);        //Create a pipe 
proc1 = fork(); 

//Child process 1 
if (proc1 == 0) 
{ 
    close(fd[0]);       //process1 doenst need to read from pipe 
    close(STD_INPUT);      //prepare for output 
    dup(fd[1]);        //Standard output = fd[1] 
    close(fd[1]); 
    execvp(parameter[0], parameter);  //Execute the process 
} 

else 
{ 
    proc2 = fork(); 
    if (proc2 == 0) 
    { 
     close(fd[1]); 
     close(STD_OUTPUT); 
     dup(fd[0]); 
     close(fd[0]); 
     execvp(parameter2[0], parameter2); 
    } 
     //Parent process 
    else 
    { 
    waitpid(-1, &status, 0);   //Wait for the child to be done 
    } 
} 

我試圖重定向一個子進程到另一個的輸出,但我想我犯了一個錯誤,在第二子進程的管道,因爲當我運行程序與第二個子進程我得到不正確的結果(像一個簡單的執行,如「ls」執行不當),但是,如果我刪除第二個子進程,程序運行良好(不包括管道,只是簡單的fork:ls,ls -l,ps等)。

回答

2

我可以給出的最佳答案是Beej's Guide to Unix IPC

醚酮(PEEK在4.3節,在那裏,他給出了一個非常相似的示例,你問的問題...)

0

在子過程1設置,close(STD_INPUT); dup(fd[1]);將複製fd[1]到最低可用描述符,它是0 (STD_INPUT)而不是1(STD_OUTPUT)。你不想關閉STD_OUTPUT嗎?另外,我建議dup2(fd[1], STD_OUTPUT)代替這個序列;它會做你想做的事情,而且無論如何都更清晰。

同樣,子進程2使用STD_OUTPUT,你可能想要STD_INPUT