多个fork语句如何工作?

时间:2013-01-29 12:44:37

标签: c unix fork

如果我运行以下代码:

#include <stdio.h>
#include <unistd.h>

int main()
{
    pid_t pid, pid1;
    fflush(stdout);
    pid = fork();
    fflush(stdout); 
    pid1 = fork();
    if(pid==0)
    {
         printf("%d is the first child\n", getpid() );
    }
    else if(pid>0)
    {
         printf("%d is the first parent\n", pid);
        wait();
    }
    if(pid1==0)
    {
         printf("%d is the second child\n", getpid() );
    }
    else if(pid1>0)
    {
         printf("%d is the second child\n", pid1);
        wait();
    }

    return 0;
}

我得到了输出:

2896 is the first parent
2896 is the first child
2898 is the first child
2898 is the second child
2898 is the second child
2896 is the first parent
2897 is the second child
2897 is the second child

我无法理解输出。为什么多次打印相同的字符串?

3 个答案:

答案 0 :(得分:8)

你正在做总共3个分叉:首先,pid = fork()在原始过程中完成,导致另外一个进程,所以总共现在为2,都从代码中的下一行继续。

然后pid1 = fork()完成了这两个,导致两个更多子进程,所以total现在为4,每个再次继续到下一行(first if)。

然后所有三个进程处理两个if-else语句(假设没有fork错误),每个进程打印两行。所以四个过程乘以2行是8行。你得到了什么。

所以流程是:

  • 原始
  • 第一代年龄较大的孩子,来自1st fork声明
  • 第一代小孩,来自原来的第二代声明
  • 第二代孩子,来自老一代孩子的第二代声明

如果您想了解输出,请在脑海中逐步完成所有这四个过程的代码。除了您现在打印的内容之外,如果您在每个打印语句中打印出当前的pid,它也可能会有所帮助。

答案 1 :(得分:0)

另外我认为你在下面的代码中错误地打印了相同的字符串

else if(pid1>0)
{
    printf("%d is the second child\n", pid1); // This "child" should be "parent"
    wait();
}

答案 2 :(得分:0)

为了更好地理解,您可以为每个进程编写if / else块:

    if(pid != 0 && pid1 != 0){
        printf("Parent P\n");//parent
    }else if(pid == 0 && pid1 != 0){
        printf("First child of P\n");
    }else if(pid != 0 && pid1 == 0){
        printf("Second child of P\n");
    }else{
        //pid = 0, pid2 = 0
        printf("Child of the first child of P\n");
    }