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

问题描述

考虑一个简单的code:

Consider this simple code:

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

当孩子增加MYVAR,与父亲(如pthread的)共享的价值?

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

推荐答案

没有,是的。

没有,它们不以任何方式是对程序员可见共享;流程可以独立修改自己的变量副本,他们会更改,恕不对其他进程(ES),这是fork()的父母,兄弟姐妹或后代的任何noticable效果。

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.

但是,是,操作系统实际上做初始共享的网页,因为叉实现写入时复制这意味着该过程没有提供修改网页,它们是共享的。这是,然而,它可以忽略不计的优化。

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.

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

08-13 10:10