我正在学习使用 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: %un", getpid());
else {
printf("I am the parent: %u and my child is: %un", 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() 时,输出更加奇怪。有人可以向我解释一下吗?
fork fork fork
1183----+---------------+----------------+-------------------->
| | |
| | 1186 +-------------------->
| |
| 1185 +----------------+-------------------->
| |
| 1189 +-------------------->
|
1184 +---------------+----------------+-------------------->
| |
| 1188 +-------------------->
|
1187 +----------------+-------------------->
|
1190 +-------------------->
用 http://www.asciiflow.com/#Draw 创建