fork()系统以哪种方式调用制作子进程? [英] In what manner, fork() system call making child process?
本文介绍了fork()系统以哪种方式调用制作子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的fork()系统调用代码,
Here is my code for fork() system call,
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
int main(int argc, char *argv[])
{
pid_t pid;
pid=fork();
printf("1st Fork\n");
printf("Process ID : %d, Parent Process ID : %d\n",getpid(),getppid());
pid=fork();
printf("2nd Fork\n");
printf("Process ID : %d, Parent Process ID : %d\n",getpid(),getppid());
pid=fork();
printf("3rd Fork\n");
printf("Process ID : %d, Parent Process ID : %d\n",getpid(),getppid());
return 0;
}
运行代码时,我得到的输出类似
While running the code, i am getting output like
1st Fork
Process ID : 3393, Parent Process ID : 3392
2nd Fork
Process ID : 3394, Parent Process ID : 3393
3rd Fork
Process ID : 3395, Parent Process ID : 3394
3rd Fork
Process ID : 3394, Parent Process ID : 3393
2nd Fork
Process ID : 3393, Parent Process ID : 3392
3rd Fork
Process ID : 3397, Parent Process ID : 3393
3rd Fork
Process ID : 3393, Parent Process ID : 3392
1st Fork
Process ID : 3392, Parent Process ID : 3440
2nd Fork
Process ID : 3398, Parent Process ID : 3392
3rd Fork
Process ID : 3400, Parent Process ID : 3398
3rd Fork
Process ID : 3398, Parent Process ID : 3392
2nd Fork
Process ID : 3392, Parent Process ID : 3440
3rd Fork
Process ID : 3401, Parent Process ID : 3392
3rd Fork
Process ID : 3392, Parent Process ID : 3440
为什么这个fork()系统调用进行8处理,以及如何进行?
Why this fork() system call making 8 process and how?
我也正在执行14个printf()语句执行.为什么?
Also i am getting 14 printf() statement executions. Why?
推荐答案
每次调用fork
时,它将返回两次.一次进入父级,一次进入新流程.然后继续进行操作,它们又重新分叉.
Each time you call fork
it returns twice. Once in the parent, once in a new process. Then as they go on, they both fork again.
您很有可能没想到孩子再次分叉.对于每个fork
,您通常具有:
It's most likely you didn't expect the children to fork again. With each fork
you usually have:
switch (fork()) {
case -1:
/* ERROR. */
break;
case 0:
/* Child process. */
break;
default:
/* Parent. */
break;
}
在您的代码中是这样的:
In your code it's like this:
- 您有一个流程,然后它分叉
- 您现在有两个流程,并且两个都是 fork
- 您现在有4个流程,并且所有流程都分叉
- 您现在有8个流程,您正在就SO提出问题
- You have one process, then it forks
- You now have two processes and both fork
- You now have 4 processes and all of them fork
- You now have 8 processes and you're asking questions on SO
这篇关于fork()系统以哪种方式调用制作子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文