叉(); C 中的方法

Fork(); method in C

我正在学习操作系统 class,我们正在学习分叉。我在处理一个特定示例时遇到了一些麻烦。我在网上找不到任何具体说明我需要什么的内容。希望这里有人可以提供帮助。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1, pid2, pid3;
    pid1=0, pid2=0, pid3=0;
    pid1= fork();
    if(pid1==0){
        pid2=fork();
        pid3=fork();
    } else {
        pid3=fork();
        if(pid3==0) {
            pid2=fork();
        }
        if((pid1 == 0)&&(pid2 == 0))
            printf("Level 1\n");
        if(pid1 !=0)
            printf("Level 2\n");
        if(pid2 !=0)
           printf("Level 3\n");
        if(pid3 !=0)
           printf("Level 4\n");
       return 0;
    }
}

谁能给我解释一下?我知道进程是 运行 并行的,但不确定哪个进程会 运行 首先。我的问题是了解每个分叉后的值。

所以当第一个 fork returns 时,现在有 2 个进程,Parent 和 Child。 child 获取 Parent 的所有内容。所以 parent 有 pid1、pid2、pid3 = 0 对吧?和child有一样吗?我有一个程序的输出。如果我知道第一次分叉之后发生了什么,我想我可以解决剩下的问题。

很难猜出哪部分需要解释,但作为基本概述,fork() 将当前进程复制为 "child." 原始 (parent) 进程得到 return 值等于来自操作系统的 child 的进程 ID 或 -1 如果调用失败。 child,从代码中的相同位置开始,获得 return 值 0,因为它没有 child.

操作系统对进程的调度具有完全的控制权,所以无法提前猜测哪个进程运行,但是进程ID可以用来确定children的状态。

代码非常抽象,并不能真正达到 non-example 目的。但是由于它调用了 fork() 五次,它会被主进程调用一次,each 被 parent 和 child 调用一次(总共两次),parent、children 和 grandchild 各一次(四次),依此类推。这些应该与发出 Level 消息的次数有关。

让我来命名叉子:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1, pid2, pid3;
    pid1=0, pid2=0, pid3=0;
    pid1= fork(); /* A */
    if(pid1==0){
        pid2=fork(); /* B */
        pid3=fork(); /* C */
    } else {
        pid3=fork(); /* D */
        if(pid3==0) {
            pid2=fork(); /* E */
        }
        if((pid1 == 0)&&(pid2 == 0))
            printf("Level 1\n");
        if(pid1 !=0)
            printf("Level 2\n");
        if(pid2 !=0)
           printf("Level 3\n");
        if(pid3 !=0)
           printf("Level 4\n");
       return 0;
    }
}

那么,执行将是:

----A----D--------- (pid1!=0, pid2==0(as initialized), pid3!=0, print "Level 2" and "Level 4")
    |    |
    |    +----E---- (pid1!=0, pid2!=0, pid3==0, print "Level 2" and "Level 3")
    |         |
    |         +---- (pid1!=0, pid2==0, pid3==0, print "Level 2")
    |
    +----B----C---- (pid1==0, pid2!=0, pid3!=0, print nothing)
         |    |
         |    +---- (pid1==0, pid2==0, pid3==0, print nothing)
         |
         +----C---- (pid1==0, pid2==0, pid3!=0, print nothing)
              |
              +---- (pid1==0, pid2==0, pid3==0, print nothing)