问题描述
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;
}
输出:
Init
pre fork()Parrent PID:4788
pre fork()Child PID:0
我有一个Unix操作系统的过程(Ubuntu的在我的情况)。我不能为我的生活了解如何工作的。我知道叉()
函数把我的程序在两个过程,但来自哪里?它创建一个新的进程和运行整个的主要功能,如果是,为什么做了的init()
只运行一次,的printf()
两次?
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?
为什么在的printf(pre叉());
运行两次和的init()
函数只有一次?
Why does the printf("pre fork()");
run twice and the init()
function only once?
推荐答案
有只有一个过程,直到叉。也就是说,只执行一次该路径。叉后有2个进程,以便以下的系统调用code是由两个进程执行。你忽略了什么是,无论终止,都将调用退出
。
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
.
在您的code你不冲水 STDIO
。所以,这两个过程做(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.
试试这个:
printf("pre fork()\n");
^^ should flush stdout
也许
printf("pre fork()\n");
fflush(stdout);
这篇关于Unix的fork()系统调用什么时候运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!