recategorized by
849 views
1 votes
1 votes

Assume the following program is compiled and run on a modern Linux machine:

main()
{
    int x = 0;
    int a = fork();
    x++;
    if (a == 0)
    {
        a = fork();
        x++;
    }
    else
    {
        x++;
    }
    printf("GATE!\n");
    printf("x is %d\n", x);
}

What will be the largest value of $x$ displayed by the program? (Assuming $\text{fork()}$ never fails).

  1. Due to race conditions, $"x"$ may have different values on different runs of the program.
  2. $2$
  3. $3$
  4. $5$
recategorized by

2 Answers

2 votes
2 votes

each new process has it's own copy , with value before fork in it. please refer

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void forkexample()
{
    int x = 1;

    if (fork() == 0)
        printf("Child has x = %d\n", ++x);
    else
        printf("Parent has x = %d\n", --x);
}
int main()
{
    forkexample();
    return 0;
}

output

Parent has x = 0
Child has x = 2
     (or)
Child has x = 2
Parent has x = 0

 

hence in above example

I ran this program compiler 4 5 times. it gave 2 only

 

0 votes
0 votes
After first $\text{fork(): 2}$ processes will create. Only child calls second $\text{fork()}$ creating a third process. Total $3$ process will create.
Parent    process: $x=0; \: x++; \: x++; \rightarrow x=2.$
Child    process: $x=0 (\text{ after fork()}); x++; x++; \rightarrow x=2.$
Grandchild: $x=1 (\text{ after fork()}); x++; \rightarrow x=2$.
Answer:

Related questions

1 votes
1 votes
1 answer
2
Applied Course asked Jan 16, 2019
705 views
$\begin{array}{l} A = 2000 \\ B = A - 999 \\ C = A + B - 998 \\ D = A + B + C - 997 \\ \vdots \\ \vdots \\ Z = A + B + C + \dots + Y - 975 \end{array}$How much $\frac{Z+1...
1 votes
1 votes
0 answers
3
Applied Course asked Jan 16, 2019
955 views
What is the maximum number of activation records inserted into stack while converting following infix expression to postfix expression is Infix expression: $\text{7+5*3^2...