unix fork()系统调用什么时候运行?

unix fork()系统调用什么时候运行?,第1张

概述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')

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;}

输出:

Initpre fork()Parrent PID:4788pre fork()Child PID:0

我在Unix *** 作系统中有一个进程(在我的例子中是Ubuntu).我不能为我的生活理解这是如何运作的.我知道fork()函数在两个进程中分割我的程序但是从哪里来?它是否创建了一个新进程并再次运行整个main函数,如果是这样,为什么init()只运行一次而printf()运行两次?

为什么是printf(“pre fork()”);运行两次,init()函数只运行一次?

最佳答案在fork之前只有一个进程.也就是说,该路径只执行一次. fork之后有2个进程,因此系统调用之后的代码由两个进程执行.你忽略的是两个都终止,两者都会调用exit.

在您的代码中,您不会刷新stdio.所以这两个进程都这样做(退出刷新stdio缓冲区) – 这就是你看到输出的原因.

试试这个:

printf("pre fork()\n");                  ^^ should flush stdout

或者可能

printf("pre fork()\n");fflush(stdout);
总结

以上是内存溢出为你收集整理的unix fork()系统调用什么时候运行?全部内容,希望文章能够帮你解决unix fork()系统调用什么时候运行?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/1048102.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存