In fork() which will run first, parent or child?

fork

Solution

Apparently whatever scheduler you're running decides, and it can vary.

I can say from experience that if you assume that one of the two processes always runs first, you will introduce some very subtle race conditions. Either synchronize on something, like a special message on the pipe, or don't assume that either one runs first.

Problem

When the following code runs, I understand the parent and child both will run in parallel immediately after fork() is called. ``` #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <unistd.h> int main(void) { int pfds[2]; char buf[30]; pipe(pfds); if (!fork()) { printf(" CHILD: writing to the pipe\n"); write(pfds[1], "test", 5); printf(" CHILD: exiting\n"); exit(0); } else { printf("PARENT: reading from pipe\n"); read(pfds[0], buf, 5); printf("PARENT: read \"%s\"\n", buf); wait(NULL); } return 0; } ``` That means child will execute: ``` printf(" CHILD: writing to the pipe\n"); ``` And the parent will execute ``` printf("PARENT: reading from pipe\n"); ``` In parallel. For those not familiar with `C`, in `sh`: ``` $ sh -c 'echo CHILD & echo PARENT; wait' PARENT CHILD ``` So I ran this code on a single core cpu and also on dual core, but I noticed that parent is always getting printed first. Since the two are in parallel, it is quite reasonable to expect random order. But it is not happening like that. Why is it like that?

Original source