void child(int pid){
printf("Child PID:%d\n",pid);
exit(0);
}
void parent(int pid){
printf("Parent PID:%d\n",pid);
exit(0);
}
void init(){
printf("Init\n");//runs before the fork
}
int main(){
init();//only runs for parent i.e. runs once
printf("pre fork()");// but this runs for both i.e. runs twice
//why???
int pid = fork();
if(pid == 0){
child(pid); //run child process
}else{
parent(pid);//run parent process
}
return 0;
}
output:
Init
pre fork()Parrent PID:4788
pre fork()Child PID:0
I have a process in a Unix OS (Ubuntu in my case). I can't for the life of me understand how this works. I know the fork()
function splits my programs in two processes but from where? Does it create a new process and run the whole main function again, and if so why did the init()
only run once and the printf()
twice?
Why does the printf("pre fork()");
run twice and the init()
function only once?