2011-10-20 45 views
2

可能重複:
Pipe in C UNIX shell用C創建管

我試圖創建2子進程之間的管道: Child1關閉輸入和輸出管 CHILD2關閉輸出並接受輸入:

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

     //Child process 1 
     if (proc1 == 0) 
     { 
      close(fd[0]);       //process1 doenst need to read from pipe 
      dup2(fd[1], STD_OUTPUT); 
      close(fd[1]); 
      execvp(parameter[0], parameter);  //Execute the process 
     } 

     //Create a second child process 
     else 
     { 
      //Child process 2 
      proc2 = fork(); 
      if (proc2 == 0) 
      { 
       close(fd[1]); 
       dup2(fd[0], STD_INPUT); 
       close(fd[0]); 
       execvp(parameter2[0], parameter2); 
      } 
      //Parent process 
      else 
      { 
      waitpid(-1, &status, 0);   //Wait for the child to be done 
      } 
     } 

Howev呃,我在某個地方出了問題,我不知道到底在哪裏(沒有任何錯誤,它更多的是邏輯錯誤)

回答

2

管道倒退。 fd[1]用於書寫,fd[0]用於閱讀。

附註:pipe(&fd[0]);看起來有點奇怪... pipe(fd);是等價的,但(對我的眼睛)更清晰。

+1

so dup2(fd [1],STD_OUTPUT)應該是:dup2(fd [1],STD_INPUT)? – user1003749

+0

是的,雖然你可以使用預定義的宏'STDIN_FILENO'和'STDOUT_FILENO'。 –