Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

c - How many processes are created with these fork() statements?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 creates an additional processes. You now have two processes.
  2. Fork #2 is executed by two processes, creating two processes, for a total of four.
  3. Fork #3 is executed by four processes, creating four processes, for a total of eight. Half of those have pid==0 and half have pid != 0
  4. 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.
  5. Fork #5 is executed by all twelve of the remaining processes, creating twelve more processes; you now have twenty-four.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...