2010-02-16 54 views
2

學習如何使用fork()命令以及如何在父級和子級之間傳輸數據。我正在嘗試編寫一個簡單的程序來測試fork和pipe函數的工作方式。我的問題似乎是等待函數的正確使用/放置。我希望父母等待其兩個孩子完成處理。下面是代碼我迄今:如何在分叉多個進程時使用wait()函數?

int main(void) 
{ 
    int n, fd1[2], fd2[2]; 
    pid_t pid; 
    char line[100]; 

    if (pipe(fd1) < 0 || pipe(fd2) < 0) 
    { 
     printf("Pipe error\n"); 
     return 1; 
    } 

    // create the first child 
    pid = fork(); 

    if (pid < 0) 
     printf("Fork Error\n"); 
    else if (pid == 0) // child segment 
    { 
     close(fd1[1]); // close write end 
     read(fd1[0], line, 17); // read from pipe 
     printf("Child reads the message: %s", line); 

     return 0; 
    } 
    else // parent segment 
    { 
     close(fd1[0]); // close read end 
     write(fd1[1], "\nHello 1st World\n", 17); // write to pipe 

     // fork a second child 
     pid = fork(); 

     if (pid < 0) 
      printf("Fork Error\n"); 
     else if (pid == 0) // child gets return value 0 and executes this block 
      // this code is processed by the child process only 
     { 
      close(fd2[1]); // close write end 
      read(fd2[0], line, 17); // read from pipe 
      printf("\nChild reads the message: %s", line); 
     } 
     else 
     { 
      close(fd2[0]); // close read end 
      write(fd2[1], "\nHello 2nd World\n", 17); // write to pipe 

      if (wait(0) != pid) 
       printf("Wait error\n"); 
     } 

     if (wait(0) != pid) 
      printf("Wait error\n"); 

    } 

    // code executed by both parent and child 
    return 0; 
} // end main 

目前我輸出看起來沿着線的東西:

./fork2 
Child reads the message: Hello 1st World 
Wait error 

Child reads the message: Hello 2nd World 
Wait error 

哪裏是合適的地方,使家長等待?

感謝,

託梅克

+0

你好,我正在做一個目前使用管道的項目。你能否解釋一下當main處於最後一個else語句時,main是如何將信息傳遞給你的第一個子進程的? – TwilightSparkleTheGeek 2014-06-25 18:41:57

回答

4

這似乎大多是OK(我沒有運行它,請注意)。你的邏輯錯誤是假定孩子會以某種特定的順序結束;除非你確定你知道你將找回哪一個,否則不要檢查wait(0)對某個特定pid的結果!

編輯:

我跑你的程序;您確實至少有一個錯誤,您的第二個子進程調用wait(),您可能不想這麼做。我建議你將一些代碼分解成函數,這樣你可以更清楚地看到你正在執行的操作的順序,而沒有任何混亂。

+2

+1。如果你想等待一個特定的進程退出,使用'waitpid()'。 – 2010-02-16 05:58:13

+0

@T。耶茨,'waitpid()'岩石。 – 2010-02-16 06:00:38

0

我認爲它更好地使用這樣的東西,以等待所有的兒童。

int stat; 
while (wait(&stat) > 0) 
    {} 
+1

請以最小工作示例的形式提供您的答案。例如,在這裏我不知道'while'陳述在哪裏。在所有叉子之後?每次分岔後?此外,是否只有父母必須執行此操作? – puk 2013-11-11 21:35:53