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$
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().