fork后,全局变量是否共享? [英] After forking, are global variables shared?

查看:167
本文介绍了fork后,全局变量是否共享?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个简单的代码:

 int myvar = 0;
 int main() {
     if (fork()>0) {
       myvar++;
     } else {
       // father do nothing
     }
 }

child 递增 myvar 时,值是否与父亲共享(如 pthread)?

When child increments myvar, is the value shared with the father (like pthread)?

推荐答案

否,是.

不,它们不会以程序员可见的任何方式共享;进程可以独立地修改它们自己的变量副本,并且它们会改变而不会对其他进程(fork() 父进程、兄弟进程或后代进程)产生任何明显影响.

No, they are not shared in any way which is visible to the programmer; the processes can modify their own copies of the variables independently and they will change without any noticable effect on the other process(es) which are fork() parents, siblings or descendents.

但是,是的,操作系统最初确实会共享页面,因为 fork 实现了写时复制,这意味着只要没有进程修改页面,它们就会被共享.然而,这是一个可以忽略的优化.

But yes, the OS actually does share the pages initially, because fork implements copy-on-write which means that provided none of the processes modifies the pages, they are shared. This is, however, an optimisation which can be ignored.

如果您想拥有共享变量,请将它们放在匿名共享映射中(请参阅 mmap()),在这种情况下,它们真的会被共享,以及随之而来的所有警告.

If you wanted to have shared variables, put them in an anonymous shared mapping (see mmap()) in which case they really will get shared, with all the caveats which come with that.

这篇关于fork后,全局变量是否共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆