Latest

6/recent/ticker-posts

What is the output of the following code- fork() system call

What is the output of the following code- fork() system call


 #include <stdio.h>

#include<unistd.h>

int main()

{

    if(fork()     &&     fork())

        fork();

    printf("Hi  ");


    return 0;

}

OUTPUT: Hi    Hi    Hi    Hi


EXPLANATION:

When the first fork() inside the conditional statement will execute, then two processes will be cloned, one is child process C1  with logic 0 and another is the parent process P with logic +1. Both the processes will run parallelly.

For C1, the logic of C1 is  0 , So, the logic of the conditional statement will be zero and the second fork() and third fork() will not be executed. The program will simply output Hi.

For P, the logic of P is 1, so the second fork() call will be executed and it will again create two processes, one is child process C2 and another is parent process P.

C2 will simply print Hi as C1.

In P, the logic of the conditional statement will be 1, so the third fork() will be called and it will again create one child process C3 and parent process P. Both of them will return Hi.

So, the output of the program will be

Hi    Hi    Hi    Hi
C1    C2    C3    P




Post a Comment

0 Comments