在fork()情况下的全局变量值 [英] Global variable value in case of fork()

查看:142
本文介绍了在fork()情况下的全局变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我遇到了一个有趣的情况:

Lately I've encountered an interesting situation:

我已经在动态链接库(.so)中定义了一个全局静态变量.该库总是在fork()下调用.

I've defined a global static variable in a dynamically linked library (.so). This library always being called under fork().

我注意到的是,全局变量始终使用init值进行调用,并且不会在调用之间更改它们.

What I've noticed is that the global variable always being called with init values, and doesn't change them between the calls.

我对此有一些疑问:

  1. 为什么分叉"会更改此变量的内存更新基本方法?我以为全局变量具有特定的内存映射

  1. Why does being 'forked' change the basic method of memory update for this variable? I thought that global variable has a specific memory mapping

是否有人熟悉绕过该方法的方法?我只想到了一种将数据写入内核内存空间的方式(使用mmap)

Is anyone familiar with a method to bypass it? I only thought on a way in which I write the data to Kernel memory space (using mmap)

谢谢大家!

推荐答案

发出 fork()复制要在子进程中使用的用户空间(这是文件句柄和未更改的变量的例外)-参见写时复制).因此,您的孩子的全局变量在派生时将具有父级的值,但它是自己的变量.更改变量不会影响父级(或更新父级不会影响子级).这是使用fork的原因之一.

Issuing fork() copies the user space for use in the child process (the exception to this is file handles, and unchanged variables - see copy on write). So, your childs global variables will have the value of the parent at the time of fork, but it's own variable. Changing the variable will not effect the parent (or updating the parent will not effect the child). The is one of the reasons for using fork.

如果您确实需要在父子之间共享数据,请查看专门为此目的设计的共享内存方法.我不会直接尝试很多心理方面的事情.

If you really need to share data between parent and child look at shared memory methods specifically designed for the purpose. I wouldn't try and much with mental space directly.

这篇关于在fork()情况下的全局变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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