Reputation: 455
I'm using this code in both Linux and in Cygwin (on Windows) and the output order is different and I have no clue why..
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t pid;
/* fork a child process */
pid = fork();
printf("\n PID1 %d\n",pid);
pid = fork();
printf("\n PID2 %d\n",pid);
return 0;
}
the output in windows is:
PID1 3888
PID1 0
PID2 5564
PID2 7772
PID2 0
PID2 0
but in Linux (and MAC) it looks like
PID1 2486
PID2 2487
PID2 0
PID1 0
PID2 2488
PID2 0
My question is PID2 ( PID2 2487) comes before PID1 in Linux but not in Windows (the output behavior is the same every time I run the code)
Upvotes: 0
Views: 3459
Reputation: 3134
After a fork(), it is indeterminate which process—the parent or the child—next has access to the CPU.On a multiprocessor system, they may both simultaneously get access to a CPU.An operating system can allow you to control this order. For instance, Linux has /proc/sys/kernel/sched_child_runs_first.
Upvotes: 4
Reputation: 179687
The order in which the processes run in post-fork is unspecified.
Upvotes: 3