c++ - C++ 中的 fork() 学习操作系统开发

标签 c++ operating-system

我正在学习使用 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

I am the parent: 1183 and my child is: 1186

user@slacker:~$ I am the parent: 1184 and my child is: 1188

I am the parent: 1185 and my child is: 1189

I am the parent: 1187 and my child is: 1190

I am the child: 1186

I am the child: 1189

I am the child: 1190

I am the child: 1191

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

最佳答案

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

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

关于c++ - C++ 中的 fork() 学习操作系统开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672720/

相关文章:

c - 中断 vector 处理程序地址

java - 为什么这个Java小程序会让MacOS重启?

c++ - 从 C++ 将 uint8_t* buffer 和 size_t bufferlen 传递给 C 中的 API 函数的最佳方法是什么

c++ - 使用 valgrind+kcachegrind 缩短分析结果中的函数名称

c++ - 我的 do while 循环只执行一次

linux - 操作系统漏洞示例

linux - 为什么现代操作系统需要这么多内存?

x86 - 多级分页如何节省内存?

C++ 函数 - 错误 : '0' cannot be used as a function

c++ - 防止 C++ 库链接过期