程序的进程图清楚地显示了父进程和子进程从创建到终止的执行情况

Process Graph for the program clearly showing the parent and child processes execution from creation to termination

pid_t pid;
printf("Begin");
if (fork() == 0) {
    printf("First if fork==0");
    if (fork() != 0) 
        printf("First if fork!=0");
}

if (fork() != 0) {   
    printf("second if fork!=0");
    if (fork() == 0) 
        printf("second if fork==0");
}

printf("End if\n");

我试图了解 fork 的工作原理。 你能画出一张我和其他人都能理解的流程图吗?

您的示例有 四个 fork。通常这是不同的做法

pid_t child_pid = fork();
// both parent and child process return from `fork()` and continue here
if (child_pid == -1) {
    // still parent process, error handling
    // no child process was created
} else if (child_pid == 0) {
    // this is the child process
} else {
    // this is the parent process, child_pid > 1
}

现在你可以清楚地看到,parent中的代码是运行,child中的代码是运行。


回到您的示例,您有一个主进程执行 forks(忽略错误处理)

if (fork() == 0) {
    printf("First child process\n");
    if (fork() != 0)
        printf("First child process (parent part)\n");
    /*
    else
        printf("Grandchild\n");

    // fall through for both first child and grandchild
    */
}

// Main process, and first child, and grandchild
if (fork() != 0) {
    // also first child and grandchild ("parent" part)
    printf("Main process (parent part)\n");
    if (fork() == 0)
        // also third grandchild, and second great-grandchild
        printf("Third child process\n");
}
/*
else
    // also second grandchild, and first great-grandchild
    printf("Main process, second child\n");
*/

这意味着,你有一个主进程,有三个 children。 child 进程中的第一个进程也进行了分叉,创建了一个 grandchild.


但是,第一个 child 和第一个 grandchild 继续使用相同的代码到第二个外部 if,因此创建额外的 children,grandchildren, 和 great-grandchildren.

所以,最后主进程有3个children。从第一个child开始,三个大child人下降,其中第一个child有两个great-grandchildren。

除非我忘了一两个左右,当然:-)