簡體   English   中英

管道在C UNIX shell中

[英]Pipe in 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等)。

我能給出的最佳答案是Beej的Unix IPC指南

(看看第4.3節,他給出了一個與你問的問題非常相似的例子......)

在子進程1設置中, close(STD_INPUT); dup(fd[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

暫無
暫無

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

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