这些 fork() 语句创建了多少个进程? [英] How many processes are created with these fork() statements?

查看:54
本文介绍了这些 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

  1. Fork #1 创建了一个额外的进程.您现在有两个进程.
  2. Fork #2 由两个进程执行,创建两个进程,总共四个.
  3. Fork #3 由四个进程执行,创建四个进程,总共八个.其中一半有 pid==0,一半有 pid != 0
  4. fork #4 由 fork #3 创建的一半进程执行(因此,其中四个).这会创建四个额外的过程.您现在有十二个进程.
  5. Fork #5 由所有剩余的 12 个进程执行,从而再创建 12 个进程;你现在有二十四个了.

这篇关于这些 fork() 语句创建了多少个进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆