This question was a part of my Mid-Sememter Exams, and its answer as given by the prof is quite absurd.
I just want to know what is correct answer.
CODE:
#include<unistd.h>
// Other Libraries
void ChildProc()
{
sleep(10);
printf("Child Process\n");
}
void ParentProc()
{
printf("Parent Process");
}
int main()
{
pid_t pid;
pid = fork();
if(pid==0)
ChildProc();
else
ParentProc();
return 0;
}
QUESTION: What are all the possible outputs of the following code?
My answers were,
1)
OUTPUT: None
REASON: When the fork fails.(System does not allow creation of a child process)
2)
OUTPUT: Parent Process
REASON: As both parent and child are now in race condition. Who ever may execute first, the parent finishes early and thus would exit the function, and then the program itself will exit. Now the child can't stay alive when the parent ended. Thus it also ends.
But the prof considered another state, when the child starts execution first and starts the sleep loop. Now on the parent's turn, the processor is too busy and thus keeps the process in pending state for ~10seconds. Now by this time the child completes the sleep and resumes execution, and gradually parent executes and thus the output is,
OUTPUT:
Child Process
Parent Process
Though probability of this happening is very very very rare, and only when the process context switcher is very busy but still he says it is possible? Now i am not convinced with his reasoning, and what to know is it really possible, at least in now-a-days linux OS ??