371 views

What will be the output of the following piece of code?

Void foo()
{
int i=1;
fork();
i++;
printf(“%d”,i);
fork();
i++;
printf(“%d”,i);
fork();
i++;
printf(“%d”,i);
}
1. $2 \ 2 \ 3 \ 3 \ 3 \ 3 \ 4 \ 4 \ 4 \ 4 \ 4 \ 4 \ 4 \ 4$
2. $2 \ 3 \ 3 \ 2 \ 3 \ 4 \ 4 \ 4 \ 3 \ 4 \ 4 \ 4 \ 4 \ 4$
3. $2 \ 3 \ 4 \ 2 \ 3 \ 4 \ 4 \ 3 \ 4 \ 4 \ 4 \ 3 \ 4 \ 4$
4. All of above three options are correct

Whenever fork is called, a new process is created and statements after fork will be executed in all the processes which are available at that time.
So after 1st fork 2 processes will be there  with i=2(parent and child),

2 2
then 4 processes with i=3 after 2nd fork.

3 3 3 3
And finally after 3rd fork 8 processes will be there with i=4.

4  4  4  4  4  4  4  4

But order can be different based on whether parent process or  child process executes first.

So we can get any of first 3 options as output.
by

@Bikram sir

How many more such sequences are possible??
@sushmita could you clarify the doubt above my comment... i.e how many such sequences are possible?

@Tesla! how many such sequences possible? 8! for this question or what

1 vote