在 if/else 块中跟踪具有多个分支的程序

Tracing a program with multiple forks in if/else block

我正在尝试跟踪这个程序。当我 运行 它时,我看到它输出了 4 次,但我不明白为什么。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() 
{
    if (fork() == 0)
        fork();
    else 
    {
        fork();
        fork();
        printf("%d\n", getpid());
    }
}

据我所知,if/else 分叉我的程序,然后如果我们在 child 中,它会再次分叉。如果我们在 parent 中,它是 运行 else 块中的代码。不过,当我尝试在这一点之后进行追踪时,我会感到困惑。

经过为我解释后,我现在明白了。

第一个分支会产生一个 child(我们称它为 c1):

if (fork() == 0)

当你在 child 中时,fork 的 return 值为 0。所以,c1会执行if语句块:

fork();

这里创建的 child,c2(以及 c1)都将死亡,因为它们不会执行 else 块。


同时,parent进程将执行else块。

fork();

这将创建原始 parent 进程 (c3) 的另一个 child。 c3 将执行 else 块中的下一个 fork。

fork();

现在,我们也有 c4。


与此同时,原来的 parent 进程仍然会有一个没有 运行 的分叉。这将创建最终的 child 进程 c5。

在运行的最后会有4个打印:原始parent进程,c3,c4,c5。

  1. fork in if 被执行。现在有两个进程 child C1 和 parent。 Parent 得到一个 non-zero 号码。 Child 得到 0.

  2. Parent 进入 else 块,因为它从 fork 得到 non-zero return。现在又有两个进程 child C2 和 parent - 在 else 块中执行 fork 之后。

  3. Parents 再次与 C3 分叉。

  4. Child C2 再次与 C4 分叉。

  5. 请注意,C1 也进行了分叉,但它除了结束 if 块外不会做任何事情。 (我们不关心这个)。

因此 4printf 执行 - 一个由 Parent、C2C3C4.

关键的一行黄金法则是:-

Both parent and child process start their execution right after the system call fork()

当控制到达function的末尾时,每个进程结束,这里是main()。 (回答你的最后一个问题)。