I am learning process forking and I’m trying the code of listing 3:
sunbox$ cat fork2.c
#include <unistd.h>
#include <stdio.h>
int main (void) {
pid_t p;
printf("Original program, pid=%d\n", getpid());
p = fork();
if (p == 0) {
printf("In child process, pid=%d, ppid=%d\n",
getpid(), getppid());
} else {
printf("In parent, pid=%d, fork returned=%d\n",
getpid(), p);
}
}
sunbox$ gcc fork2.c -o fork2
sunbox$ ./fork2
Original program, pid=767
In child process, pid=768, ppid=767
In parent, pid=767, fork returned=768
The output I get:
Original program, pid=2728 In parent, pid=2728, fork returned=2731 In child process, pid=2731, ppid=2728
Whereas the sample page shows an output of child first, and then parent? I don’t understand this.
Also, when I run the code in my college lab I get output as shown on the page. Thanks a lot in advance for troubling to answer this naive question.
If it matters, I’m running Ubuntu 11.04.
After the fork() system call, it is up to the OS scheduler which process continues first. It is possible that repeated runs of this same program would result in different orders.
This is called non-determinism.