多少进程与这些fork()的语句创建? [英] How many processes are created with these fork() statements?
本文介绍了多少进程与这些fork()的语句创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我相信,这将创建24处理;不过,我需要核实。这些问题常常难倒我了。感谢您的帮助!
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&unistd.h中GT;INT主要(无效)
{
将为pid_t PID =叉();
PID =叉();
PID =叉();
如果(PID == 0)
{
叉子();
}
叉子();
返回0;
}
解决方案
这是很容易通过这个道理。在叉
调用创建每次它执行时的附加处理。调用返回 0
新(子)进程,并在原始(父)过程中的孩子(不为零)的进程ID。
将为pid_t PID =叉(); //叉#1
PID =叉(); //叉#2
PID =叉(); //叉#3
如果(PID == 0)
{
叉子(); //叉#4
}
叉子(); //叉#5
- 叉#1创建一个额外的进程。你现在有两个进程。
- 叉#2由两个进程执行时,创建两个过程,总共四个
- 叉#3由四个进程执行时,创建四个过程,总共八个。其中一半有
PID == 0
半有PID!= 0
- 叉#4是由叉#3中创建的过程中执行的一半(所以,他们四人)。这将创建四个额外的进程。您现在有十二流程。
- 叉#5被其他进程的所有十二个执行,创造再多得十几个过程;你现在有24。
I believe that this creates 24 processes; however, I need verification. These questions often stump me. Thanks for the help!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
pid = fork();
pid = fork();
if (pid == 0)
{
fork();
}
fork();
return 0;
}
解决方案
It's fairly easy to reason through this. The fork
call creates an additional process every time that it's executed. The call returns 0
in the new (child) process and the process id of the child (not zero) in the original (parent) process.
pid_t pid = fork(); // fork #1
pid = fork(); // fork #2
pid = fork(); // fork #3
if (pid == 0)
{
fork(); // fork #4
}
fork(); // fork #5
- Fork #1 creates an additional processes. You now have two processes.
- Fork #2 is executed by two processes, creating two processes, for a total of four.
- Fork #3 is executed by four processes, creating four processes, for a total of eight. Half of those have
pid==0
and half havepid != 0
- Fork #4 is executed by half of the processes created by fork #3 (so, four of them). This creates four additional processes. You now have twelve processes.
- Fork #5 is executed by all twelve of the remaining processes, creating twelve more processes; you now have twenty-four.
这篇关于多少进程与这些fork()的语句创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文