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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Init
pre fork()Parrent PID:4788
pre fork()Child PID:0
Run Code Online (Sandbox Code Playgroud)
我在Unix操作系统中有一个进程(在我的例子中是Ubuntu).我不能为我的生活理解这是如何运作的.我知道这个fork()函数在两个进程中分割我的程序但是从哪里来?它是否创建了一个新进程并再次运行整个main函数,如果是这样,为什么init()只运行一次和printf()两次?
为什么printf("pre fork()");运行两次,init()功能只运行一次?
cni*_*tar 23
在fork之前只有一个进程.也就是说,该路径只执行一次.fork之后有2个进程,因此系统调用之后的代码由两个进程执行.你忽略的是两者都终止,两者都会调用exit.
在你的代码中,你不是在冲洗stdio.所以这两个进程都这样做(退出刷新stdio缓冲区) - 这就是你看到输出的原因.
试试这个:
printf("pre fork()\n");
^^ should flush stdout
Run Code Online (Sandbox Code Playgroud)
或者可能
printf("pre fork()\n");
fflush(stdout);
Run Code Online (Sandbox Code Playgroud)