4,319 views
2 votes
2 votes
#include<stdio.h>
#include<unistd.h>
int main()
{     for(i=0;i<2;i++)
       {
          if(fork()==0) printf("hello");
       }
}

1 Answer

Best answer
15 votes
15 votes

Lets unroll the loop to explain easily

int main()
{
    if(fork() == 0) //After here there are 2 processes
        printf("Hello"); 
    if(fork() == 0) //After here there are 4 processes
        printf("Hello");
}

When a process calls fork(), a copy of that process is made (like a clone) and that copy (called a child) also starts execution from the point of call of fork (starts executing the following instruction). The only difference for these 2 processes is the return value of the fork -- which is 0 for the child one and non-zero for the parent (it will be the child pid). Thus in the given code, child only does the printing.

After first fork, we have 2 processes and one of them prints.

After the second fork, we have $2\times2 = 4$ processes, and 2 of them prints.

So, totally we get $1 + 2 = 3$ "hello".

Now, there is a catch here, as I told when fork is called a copy of the process is made. This includes every thing that is part of the process including file descriptors and buffers. So, if the output buffer is not flushed before fork, even that is copied to the child process and output gets printed more times than expected. A quick fix for this is to print "hello\n" than just "hello". (Still remember my B.Tech. day when a whole day was spent on this issue).

selected by
Answer:

Related questions

2 votes
2 votes
3 answers
2
Philosophical_Virus asked Dec 10, 2023
768 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
719 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