How many processes are created with these fork() s

2019-01-22 04:41发布

问题:

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;
}

回答1:

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.


回答2:

Calculate in this way :

Start with 1(Main Process) and for every fork make it twice if fork is not inside if(pid == 0) else add 1/2 of current process to current number of process.

In your code: 1P Got #1 fork() so double up current number of processes. Now new number of process 2P

Got #2 fork() so double up current number of processes. Now new number of process 4P

Got #3 fork() so double up current number of processes. Now new number of process 8P

Got #4 fork() but wait it's in if condition so (8+4 = 12)P

Got #5 fork() so double up the current number of processes. Now new number of process 24P



回答3:

You are correct. It's 24. Just compiled and ran it w/printf before the final return statement. Got 24 lines of output.



回答4:

This statement have 24+ child process. Each invocation of fork() results in two processes, the child and the parent. Thus the first fork results in two processes. The second fork() is reached by those two processes, yielding four processes. The final fork() is reached by those four, netting eight processes more. All but one of these processes (the original) is a child of at least one of the forks.