我正在学习使用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);
}
}
当我编译并运行它时,它按我的预期显示了4个 parent 和4个 child ,但是输出对我来说似乎很奇怪(请注意下面的粗体行表示在user @ slacker:〜$之后得到输出)。
当我尝试使用3 fork()时,输出甚至更陌生。有人可以向我解释吗?
最佳答案
fork fork fork
1183----+---------------+----------------+-------------------->
| | |
| | 1186 +-------------------->
| |
| 1185 +----------------+-------------------->
| |
| 1189 +-------------------->
|
1184 +---------------+----------------+-------------------->
| |
| 1188 +-------------------->
|
1187 +----------------+-------------------->
|
1190 +-------------------->
用http://www.asciiflow.com/#Draw创建
关于c++ - C++学习OS开发中的fork(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19672720/