本文介绍了使用这些 fork() 语句创建了多少个进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我相信这会创建 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;
}
推荐答案
通过这个推理很容易.fork
调用每次执行时都会创建一个额外的进程.调用返回新(子)进程中的 0
和原始(父)进程中子进程的进程 ID(非零).
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 创建了一个额外的进程.您现在有两个进程.
- Fork #2 由两个进程执行,创建两个进程,总共四个.
- Fork #3 由四个进程执行,创建四个进程,总共八个.其中一半有
pid==0
,一半有pid != 0
- Fork #4 由 fork #3 创建的进程的一半执行(因此,其中四个).这将创建四个额外的进程.您现在有 12 个进程.
- Fork #5 由其余 12 个进程执行,创建了另外 12 个进程;你现在有二十四个.
这篇关于使用这些 fork() 语句创建了多少个进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!