in Operating System edited by
371 views
3 votes
3 votes

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
in Operating System edited by
by
371 views

1 Answer

3 votes
3 votes
Best answer
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.
selected by

4 Comments

@Bikram sir

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

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

0
0
Answer:

Related questions