Reputation: 667
I'm studying for a midterm for my OS class and was looking at this code example. On my system (OS X Yosemite) I'm getting ONE TWO FOUR TWO THREE, so it seems like the child process runs and outputs first before the parent does, despite the lack of a wait() function. Is this expected behavior on all systems, or could it also be ONE TWO THREE TWO FOUR, or even something different?
#include <stdio.h>
#include <unistd.h>
int main()
{
int rc;
printf( "ONE\n" );
rc = fork();
printf( "TWO\n" );
if ( rc == 0 ) { printf( "THREE\n" ); }
if ( rc > 0 ) { printf( "FOUR\n" ); }
return 0;
}
Upvotes: 0
Views: 632
Reputation: 20869
It'll print ONE
, followed by:
For the parent process:
TWO
FOUR
For the child process:
TWO
THREE
The two processes are distinct with no synchronization between them. They run their due course, at their own timings.
So say if the parent was faster than the child, you could get TWO
FOUR
followed by TWO
THREE
. If the child was faster, you could get TWO
THREE
followed by TWO
FOUR
. If they're roughly the same, you could get a result where their outputs are intermixed, such as TWO
TWO
FOUR
THREE
, or any combination thereof.
Upvotes: 5