in Operating System retagged by
1,128 views
1 vote
1 vote
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

in Operating System retagged by
1.1k views

4 Comments

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

option a is only matching

2
2
please share the approach to solve this problem
0
0

@Arjun sir plz explain?? 

 

0
0

2 Answers

1 vote
1 vote
a)100 100 200 200
1 vote
1 vote
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!!

My bad, my bad.

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
1

Related questions

1 vote
1 vote
2 answers
4
Warrior asked in Operating System Nov 11, 2018
839 views
Warrior asked in Operating System Nov 11, 2018
by Warrior
839 views