in Operating System
181 views
0 votes
0 votes
how many child process will be created for the following code.how many hello and welcome will be printed

#include <stdio.h>

 void main() {  

  fork();    

fork();  

  printf("Hello \n");    

fork();  

  printf("welcome\n"); }
in Operating System
by
181 views

1 Answer

3 votes
3 votes
Best answer

The Program call $3$ fork() system call .

How the execution happen ?

After the first fork() call the we create one child process (C1) . Then parent (P) and Child (C1) both start the execution of the program form the end of first fork() call.

Now after the first fork() call we have currently two process one child(C1) and the parent process(P) both start executing concurrently.

Now both C1 and P call the second fork() system call .

Now when C1 call the second fork() it will create one child say C2 and when P execute the second fork() it will create another child say C3.

So , after the second fork() statement , there are 4 process executing namely P,C1,C2,C3.

So each process now execute the Printf(“Hello\n”) statement.

so 4 times “Hello” will be printed.

Now last fork() call will be executed by all the 4 processes .

So ,P will create say child (C4)

      C1 will create say child (C5)

       C2 will create say child (C6)

       C3 will create say child (C7)

So after the last fork() system call There are 8 Process namely, P.C1,C2,C3,C4,C5,C6,C7 , Out of which P is the parent rest $7$ Process are child processes.

Now all the $8$ processes execute the  printf("welcome\n"); statement . So “Welcome” will be printed 8 times.

The Process creation diagram looks like ,

So,

$7$ child process will be created.

$4$ hello and $8$ welcome will be printed.

selected by

Related questions

2 votes
2 votes
2 answers
3