when I compile this code and I run it I get a result "PARENT" appears before the "CHILD". For information I'm on Linux Mint.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
void main(){
pid_t pidc ;
pidc = fork();
if(pidc < 0)
{printf("error !\n");}
else if(pidc == 0){
printf("I am the child process! \n");
}
else{
printf("I am the parent process! \n");
}
}
and this is the Result:
I am the parent process!
I am the child process!
So, someone have an idea ? and thanks.
You may be confused because the child process's if
condition occurs before the parent's if
condition.
When you call fork()
, your existing process will be cloned into a new process. The original process will receive a return value of the child's PID from the fork()
call, the child will receive a PID of 0
.
After the fork()
succeeds, the two processes will be run in parallel, effectively. To run in parallel, processes are given small slices of time during which they execute, and at the end of the execution they are temporarily frozen while another process executes. You have no way of knowing which of the two processes will be schedule to execute first. Both the parent and the child process will execute the same code starting after the fork()
call, but due to the difference in the value for pidc
they will choose different branches of the if
statement. Thus it is the first process that happens to be given a slice of execution time that will output first, the ordering of the if
statement is not relevant.