463 views
3 3 votes

Consider the following C program executed on a UNIX-like system:
 

#include <stdio.h>
#include <unistd.h>

int main() {
    int x = 1;
    
    if (fork() && fork()) {
        x = x + 2;
    } else {
        x = x + 1;
    }
    
    printf("%d\n", x);
    return 0;
}


Which of the following statements is/are correct?

  1. Exactly $3$ processes are created in total
     
  2. Exactly $4$ processes are created in total
     
  3. The value $\verb|3|$ is printed exactly once
     
  4. The value $\verb|2|$ is printed more than once

2 Answers

1 1 vote

Initial process $\text{P0}$ starts with $\mathrm{x}=1$.
 

Expression is $\verb|fork() && fork()|$ with short-circuit AND.
 

In $\text{P0}$, first $\verb|fork()|$ is executed.

$\text{P0}$ gets non-zero → evaluates second $\verb|fork()|$ .

Child $\text{C1}$ gets $0 \rightarrow$ short-circuit applies, second fork() is NOT executed in $\text{C1}$.
 

Now from $\text{P0}$'s second $\verb|fork()|$ :

Parent $\text{P0}$ gets non-zero.

Child $\text{C2}$ gets $0$.


Total processes:

$\mathrm{P0}, \mathrm{C} 1, \mathrm{C} 2 \rightarrow 3$ processes.
 

So option A is correct, option B is false.
 

Which Branch Executes:

$\text{P0}:$first fork true AND second fork true → condition true $\rightarrow x=1+2=3$

$\text{C1}:$ first fork false → goes to else $\rightarrow x=1+1=2$

$\text{C2}:$ first fork true, second fork false → condition false → else → $\mathrm{x}=1+1=2$


Output Analysis:

Value $3$ is printed once (by $\text{P0}$).

Value $2$ is printed twice (by $\text{C1}$ and $\text{C2}$).


Final Answer:

Correct options: A, C, D

Answer:
Position:
Show:

Related questions

3 3 votes
2 2 answers
416
416 views
GO Classes asked Dec 24, 2025
416 views
A counting semaphore $\verb|S|$ is initialized to $3.$Five identical processes $\text{P1}-\text{P5}$ execute the following code concurrently:wait(S); /* critical section ...
2 2 votes
2 2 answers
361
361 views
GO Classes asked Dec 24, 2025
361 views
Two processes $\text{P1}$ and $\text{P2}$ share two semaphores $\verb|S|$ and $\verb|T|$, both initialized to $1$.The code executed by the processes is:$\textbf{P1} : $wa...
4 4 votes
3 3 answers
369
369 views
GO Classes asked Dec 24, 2025
369 views
A system uses paging with the following parameters:Logical address space size $=64 \mathrm{~KB}$ Page size $=1 \mathrm{~KB}$ Physical memory size $=32 \mathrm{~KB}$ Page ...
6 6 votes
2 2 answers
380
380 views
GO Classes asked Dec 24, 2025
380 views
A demand-paged system has the following characteristics:Memory access time $\mathrm{= 200 ~ns}$ Page fault service time $=10 \mathrm{~ms}$ Probability of a page fault $\m...