A small question about fork()

Hello experts,
I am using fork() in my code but I am confused which output comes first child or parent?
I did the following code .My book shows parent first but my linux shows child first.Can anyone tell me why?

#include <stdio.h>
int main(){
int pid;
printf("I am original process with pid is %d ,My parent (Terminal) pid is %d\n",getpid(),getppid());
pid=fork();
if(pid>0)//parent starts
    {
    printf("I am parent,my pid is %d and my parent pid is %d\n",getpid(),getppid());
    }
else 
    {
    printf("I am child,my pid is %d and my parent pid is %d\n",getpid(),getppid());
    }
//both parent and child executes the next printf
printf("PID %d terminates \n",getpid());    
}

output:

mlhazan@dEBx:~/Desktop$ gcc myFork.c 
mlhazan@dEBx:~/Desktop$ ./a.out 
I am original process with pid is 13426 ,My parent (Terminal) pid is 28555
I am child,my pid is 13427 and my parent pid is 13426
PID 13427 terminates 
I am parent,my pid is 13426 and my parent pid is 28555
PID 13426 terminates 
mlhazan@dEBx:~/Desktop$ 

By definition, you cannot know whether the child or the parent prints first. Your book should explain this.

With just fork, its not guaranteed

But if you want to control the order of execution.

Try vfork - where child is guaranteed to execute first.

else with fork - try using synchronization mechanism to schedule parent or child to run first

Don't try vfork. Expecting it to sequence the processes is a famous bug. See The Single UNIX � Specification definition of vfork which says:

and...

Ahh, I didn't know about that. This is interesting. :slight_smile:

Thank you very much Per.

If you design your application correctly it shouldn't matter which comes first. When you want something to come before child's code just put it before calling fork(). If you want the parent to stop while child is executing use wait(). Finally if you want to do synchronized stuff with child and parent use IPC.

Anyway this totally depends on the implementation of fork().