-1

How many processes are created?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(){
    int i;
    for (i = 0; i < 4; i++){
        fork();
    }
    return 0;
}

I think there are 32 processes created but I want to double check that my logic is sound. The first process creates 4 processes each, with an i value of 0. Those four processes then create 3 more processes each, with a value an i value of 1. Those 3 processes then each create 2 more processes each, with an i value of 2. Those 2 processes then each create 1 more process with an i value of 3.

(4+3+3+3+3+2+2+2+1+1)+1 = 32

The plus one is for the first process.

Does this sound correct? Thanks

frillybob
  • 600
  • 2
  • 12
  • 26
  • 2
    I don't suppose you shoved a `printf("Hello\n")` somewhere in there and just started counting ? – WhozCraig Sep 22 '17 at 03:58
  • @WhozCraig I did but if I put the printf before the fork I got 15, after, 31. I don't why it would matter. – frillybob Sep 22 '17 at 04:02
  • Putting it after ensures the started process prints *before* that processes increment on the control loop and the subsequent conditional test. Putting it before will skip that step once for each new iteration on each new process. – WhozCraig Sep 22 '17 at 04:04
  • Why do you think i has a value of zero for all of the 4 children created by the eldest process? Seems to me that the value of i will be different in each child. – William Pursell Sep 22 '17 at 05:29

2 Answers2

0

As far as I know for N fork statements, the number of processes formed are 2^N.For more details on how it works, it has already been answered in the link given below:
Visually what happens to fork() in a For Loop

Kishor
  • 450
  • 8
  • 11
0

2^N-1 as for first iteration only one child will be created and from 2 iteration onwards the fork will create 2^N Childs.

Somethings like it will be created:

                  1 
            2             2
         3    3        3    3
       4 4  4  4     4  4  4  4
Zahid Khan
  • 2,130
  • 2
  • 18
  • 31