我正在使用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 我是父母: 1183,我的孩子是: 1186 用户@slacker:~$I是父母: 1184,我的孩子是: 1188 我是父母: 1185,我的孩子是: 1189 我是父母: 1187,我的孩子是: 1190 我是孩子: 1186 我是孩子: 1189 我是孩子: 1190 我是孩子: 1191
当我尝试使用3叉()时,输出就更奇怪了。有人能给我解释一下吗?
发布于 2013-10-30 02:54:35
fork fork fork
1183----+---------------+----------------+-------------------->
| | |
| | 1186 +-------------------->
| |
| 1185 +----------------+-------------------->
| |
| 1189 +-------------------->
|
1184 +---------------+----------------+-------------------->
| |
| 1188 +-------------------->
|
1187 +----------------+-------------------->
|
1190 +-------------------->用http://www.asciiflow.com/#Draw创建
https://stackoverflow.com/questions/19672720
复制相似问题