in Operating System recategorized by
566 views
1 vote
1 vote

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$
in Operating System recategorized by
566 views

2 Answers

1 vote
1 vote

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$.

2 Comments

Explain me X is work as static variable such in every fork() execution X update
0
0
Why only three child process created?
0
0
Answer:

Related questions