When the following code is executed, I understand that the parent and child will start in parallel right after calling fork ().
#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;
}
This means that the child will perform:
printf(" CHILD: writing to the pipe\n");
And the parent will execute
printf("PARENT: reading from pipe\n");
Parallel.
For those not familiar with C, in sh:
$ sh -c 'echo CHILD & echo PARENT; wait'
PARENT
CHILD
So, I ran this code on one core of the processor, as well as on a dual core, but noticed that the parent is always printed first. Since the two are parallel, it is reasonable to expect a random order. But this does not happen. Why is this so?
source
share