edited by
900 views
0 votes
0 votes
#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;
}

Total Number of Processes existing will be (Including how many parent and child process will be there) ?

Please See My Solution.

Every Fork statement will create a new child process and return 0 and we have a main process along with it.

So 

First Fork statement when executes Creates $2$ Process  ----------->  $1$ child and $1$ parent of it.

Second fork will be executed by child and parent. So child will create an extra process and parent too so Total $4$ processes in which $2$ of each are parent and children.

Third Statement likewise ----------> Total $8$ processes($4$ child + $4$ parent)

Now the child process will execute fork so $4$ child process hence give rise to $4$ extra processes leading to total of $12$ processes.

in which total $8$ parent(including the previous $4$ and $4$ child process). Now these $8$ process($4$ child + $4$ parent which were created inside if statement)  will also execute last fork which will give rise to $8$ extra process hence total of $20$ Processes ( $12$ parent and $8$ child)

and before if there were $4$ parent also which will execute outer fork statement giving rise to $4$ extra process so total $24$ Processes (12 Parent and $12$ child).

Please see my solution carefully and point out weather the number of parent and child were calculated correctly ?

edited by

1 Answer

1 votes
1 votes

For a pictorial representation, (Kindly correct me if I'm wrong)

 

Consider the dotted lines to be the uniform application of fork() through all the parents and children at an instance.

The diamonds are supposed to be the 'if' conditions.

At the end count all the lines named 'P' & 'C' in order to count the total number of processes.

Related questions

2 votes
2 votes
3 answers
2
Philosophical_Virus asked Dec 10, 2023
871 views
Int main (){fork();printf("a");fork();printf("b");return 0;}How many distinct outputs are possible of above code? And also give outputs
3 votes
3 votes
1 answer
3
24aaaa23 asked Oct 1, 2023
769 views
Consider the following code segment :int main (void) { for (int i=2; i<=5; i++) { fork( ); }printf (“GOCLASSES”);How many times “GOCLASSES” is printed by the ab...
0 votes
0 votes
0 answers
4