fork()在C++学习os开发

ngu*_*a02 2 c++ operating-system

我正在学习使用C/C++进行OS开发,我正在使用fork()方法来试验过程.我有以下代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
    fork(); //create a child process, currently total is 1 parent, 1 child
    fork(); //create a child process,currently total is 2 parents, 2 child
    pid_t pid;
    if((pid=fork()) == 0) { //fork() and assign to pid, now has 4 parents, 4 childs
        printf("I am the child: %u\n", getpid());
    else {
        printf("I am the parent: %u and my child is: %u\n", getpid(), pid);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我编译它并运行它时,它显示了4个父母和4个孩子,正如我所料,但是输出看起来很奇怪(请注意下面的粗体线,我得到用户@ slacker之后的输出:〜$).

user @ slacker:〜$ gcc forktest.c -o forktest

user @ slacker:〜$ ./forktest

我是父母:1183,我的孩子是:1186

user @ slacker:〜$我是父母:1184,我的孩子是:1188

我是父母:1185,我的孩子是:1189

我是父母:1187,我的孩子是:1190

我是孩子:1186

我是孩子:1189

我是孩子:1190

我是孩子:1191

当我尝试使用3 fork()时,输出甚至更奇怪.有人可以向我解释一下吗?

tri*_*tan 5

         fork            fork            fork
  1183----+---------------+----------------+-------------------->
          |               |                |
          |               |           1186 +-------------------->
          |               |
          |         1185  +----------------+-------------------->
          |                                |
          |                           1189 +-------------------->
          |
  1184    +---------------+----------------+-------------------->
                          |                |
                          |           1188 +-------------------->
                          |
                  1187    +----------------+-------------------->
                                           |
                                      1190 +-------------------->
Run Code Online (Sandbox Code Playgroud)

使用http://www.asciiflow.com/#Draw创建