首页 > 解决方案 > 程序的进程图清楚地显示了从创建到终止的父进程和子进程执行

问题描述

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工作的。你能画出一个让我和其他人都能理解的过程图吗? 在此处输入图像描述

标签: cfork

解决方案


您的示例有四个 forks。通常这是以不同的方式完成的

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
}

现在可以清楚的看到,哪些代码在父进程中运行,哪些在子进程中运行。


回到您的示例,您有一个执行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");
*/

这意味着,你有一个主进程,有三个孩子。第一个子进程也进行了分叉,创建了一个孙子进程。


但是,第一个孩子和第一个孙子继续使用相同的代码到第二个外部 if,因此创建了更多的孩子、孙子和曾孙。

所以,最后主进程有三个孩子。从第一个孩子开始,三个孙子后代,其中第一个孙子有两个自己的曾孙。

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


推荐阅读