Redirected
edited by
3,408 views
3 votes
3 votes

I always face problem in fork questions  please explain in detail (with theory).  Thanks 

edited by

3 Answers

Best answer
4 votes
4 votes

Same was the case with me a long ago. But I suggest you to go through all fork questions in GO, you will surely get it. Coming to the question here when if(fork() == 0) statement executes, fork() executes and a child process is created. So, At this point of time $2$ processes are in the system (one is child process and other is the parent process). Return type of child process is $0$, but Process ID of child is returned to parent.(don't worry if you don't get this line)

int a = fork();

Here $a = 0$ for child process and $a \ne 0$ for parent process.

So, When child process execures, fork() == 0 is true and Gate  is printed. And for parent process fork() == 0 is false and  2016 is printed. And note that both of these processes will execute in some order, but that order is not known.

So, when child executes first and then parent Gate2016 will be printed and When Parent executes first and then child, 2016Gate will be printed. Hence both orders are possible and thus (C) is correct answer.

selected by
0 votes
0 votes

Some clarification first, when call fork  it creates exact copy of the current program which runs on CPU independent of parent.

Both parent and child after the execution continues the execution from the same point, which is checking the value returned by the fork call. The only difference between the parent and the child will be the returned value of fork. For parent it will be the pid of the child (and not 0 as said in the question) and for child it will be 0.

Hence in this case, the if condition will evaluate TRUE for child, it will go inside the the if print the line Gate and then exit, the parent will see a non zero value, will print the 2016 and then exit. One thing to notice is that order of printing can differ as both parent and child are executing independent of each other (parent can issue a join call on the child as it knows the pid of child, which basically means that it will wait for the child to finish its operation).

In thie case, the output can be GATE2016 or 2016GATE or some garbled version of this, like GA20TE16.

However, if the code was like this:

int main(){
    int pid = fork();
    if(pid == 0){
        printf("GATE");
        exit(0);
    }
    join(pid); // not sure about the syntax
    printf("2016");
}

Then the output will always be GATE2016.

Hope this helps.

Related questions

3 votes
3 votes
1 answer
3
1 votes
1 votes
2 answers
4
♥_Less asked Jan 12, 2018
1,742 views
What is the number of child process created ?Answer given was 63, BUT i am getting 9 !