2

我正在学习使用 C/C++ 进行操作系统开发,并且我正在使用 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);
    }
}

当我编译并运行它时,它按我的预期显示了 4 个父母和 4 个孩子,但是输出对我来说看起来很奇怪(注意下面的粗线行,我在 user@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() 时,输出更加奇怪。有人可以向我解释一下吗?

4

1 回答 1

5
         fork            fork            fork
  1183----+---------------+----------------+-------------------->
          |               |                |
          |               |           1186 +-------------------->
          |               |
          |         1185  +----------------+-------------------->
          |                                |
          |                           1189 +-------------------->
          |
  1184    +---------------+----------------+-------------------->
                          |                |
                          |           1188 +-------------------->
                          |
                  1187    +----------------+-------------------->
                                           |
                                      1190 +-------------------->

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

于 2013-10-30T02:54:35.853 回答