edited by
614 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
edited by

1 Answer

Best answer
3 votes
3 votes
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
Answer:

Related questions

2 votes
2 votes
1 answer
1
Bikram asked Dec 26, 2016
264 views
Consider the following 3 processes with 3 binary semaphores with initial values $S_{0}=0, S_{1}=0, S_{2}=1$$$ \begin{array}{|c|c|c|} \hline \textbf{P} & \textbf{Q} & \tex...
2 votes
2 votes
3 answers
2
Bikram asked Dec 26, 2016
1,051 views
In a paged memory, the page hit ratio is $0.35$. The time required to service the page fault is $100$ ns. Time required to access a page in primary memory is $10$ ns.The ...
1 votes
1 votes
1 answer
4
Bikram asked Dec 26, 2016
203 views
A counting semaphore is initialized to $10$. The $6$ P(wait) operations and $4$ V(signal) operations were completed in this semaphore. The resulting value of semaphore is...