1,128 views
int main(void)
{
int var1=100;
int pid;
if(pid==fork())
var1=200;
fork();
printf("%d",var1);
return 0;
}

what could be the output ?

a)100 100 200 200

b)200 200 200 200

c)none

it should print two 100's and two 200 in any order !

option a is only matching

please share the approach to solve this problem

@Arjun sir plz explain??

a)100 100 200 200
100 100 200 200 if in first fork call child  is executed before parent otherwise  answer is  200 200 100 100 (option D)

### 1 comment

edited by
I don't know where I went wrong, please help me to make it clear.

According to me the answer should be 3 times 100 and only 1 time 200. And the sequence of the output is completely dependent of OS i.e. depending upon to whom os first provide chance to execute be it the parent or the children.

Please make it correct if it is wrong.

---Edited!!

I got it.

The concept is that newly created Child process inherits values of all the variables from its parent process. And in given case Parent process P0 is having tha value of var1 as 100 and its first child process C0 will be having the value of var1 as 200 because of the assumption of pid to be 0.

Again when fork() will be called next time , child process C1 of P0 will be having var1 as 100 , and child process of child C0 will be having var1 as 200.

That is why ans turns out to be a combination of 2 100's and 2 200's depending upon OS.

1 vote