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");
}
int main(){
init();
printf("pre fork()");
int pid = fork();
if(pid == 0){
child(pid);
}else{
parent(pid);
}
return 0;
}
output:
Init
pre fork()Parrent PID:4788
pre fork()Child PID:0
I have a process on a Unix OS (Ubuntu in my case). I canβt let my life understand how it works. I know that a function fork()separates my programs in two processes, but where from? Does he create a new process and run the entire main function again, and if so, why did he init()execute it only once and printf()twice?
Why is it executed printf("pre fork()");twice and the function init()only once?
source
share