首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++学习操作系统开发中的fork()

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

Stack Overflow用户
提问于 2013-10-30 02:24:27
回答 1查看 273关注 0票数 2

我正在使用C/C++学习操作系统开发,我正在使用fork()方法对进程进行实验。我有如下代码:

代码语言:javascript
复制
#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 用户@slacker:~$I是父母: 1184,我的孩子是: 1188 我是父母: 1185,我的孩子是: 1189 我是父母: 1187,我的孩子是: 1190 我是孩子: 1186 我是孩子: 1189 我是孩子: 1190 我是孩子: 1191

当我尝试使用3叉()时,输出就更奇怪了。有人能给我解释一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-30 02:54:35

代码语言:javascript
复制
         fork            fork            fork
  1183----+---------------+----------------+-------------------->
          |               |                |
          |               |           1186 +-------------------->
          |               |
          |         1185  +----------------+-------------------->
          |                                |
          |                           1189 +-------------------->
          |
  1184    +---------------+----------------+-------------------->
                          |                |
                          |           1188 +-------------------->
                          |
                  1187    +----------------+-------------------->
                                           |
                                      1190 +-------------------->

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19672720

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档