Reputation: 95
While reading through some articles about fork() in C, I saw this example (code below) which I couldn't understand:
Understanding problem: We only run "if" or "else" and not both. But since the child and parent processes run "simultaneoustly", in this example we see that we went through "if" and "else" both! Eventhough it's similtaneous, it isn't in reality, it depends on which one of the processes will get the CPU first (right?).
What makes everything "weirder" is that we might first go through the "else" and then through the "if". How is this possible ?
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void forkexample()
{
// child process because return value zero
if (fork() == 0)
printf("Hello from Child!\n");
// parent process because return value non-zero.
else
printf("Hello from Parent!\n");
}
int main()
{
forkexample();
return 0;
}
Possible Outputs are:
Hello from Child!
Hello from Parent!
(or)
Hello from Parent!
Hello from Child!
Upvotes: 0
Views: 140
Reputation: 62613
fork
is a system call, which does following (in abstraction, actual implementation likely to differ on the modern systems):
As a result, on the multi-core system, both parent and a child are going to be executing independently, and absent other synchronization, in no way related to each other.
And if you observe the output of those two processes, you will find out that output from those can come in any shape or form - you can have output from the parent preceding output from the child, succeeding it or being interleaved with it - it is unpredictable what you will end up seeing.
Upvotes: 2
Reputation: 225344
Remember that the fork
function actually returns twice: once to the parent with the child's pid and once to the child with 0.
At that point you have two independent processes running the same code and printing to the same terminal. And since you have two processes, the kernel is free to schedule them in any way it sees fit, meaning the output of either process can appear in any order.
Upvotes: 4