2010-02-16 20 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