问题
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?
回答1:
There's only one process until the fork. That is, that path is executed only once. After the fork there are 2 processes so the code following that system call is executed by both processes. What you ignore is that both terminate and both will call exit.
In your code you're not flushing stdio. So both processes do that (exit flushes stdio buffers) - that's why you're seeing that output.
Try this:
printf("pre fork()\n");
^^ should flush stdout
Or maybe
printf("pre fork()\n");
fflush(stdout);
来源:https://stackoverflow.com/questions/8863447/unix-fork-system-call-what-runs-when