我正在学习使用 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:~$ 之后得到输出)。
block 引用>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 +-------------------->
关于c++ - C++ 中的 fork() 学习操作系统开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672720/