Global variable value in case of fork() [duplicate]

人走茶凉 提交于 2021-01-28 07:08:38

问题


Lately I've encountered an interesting situation:

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

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

I have a few questions about that:

  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

  2. 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)

Thank you all!


回答1:


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.



来源:https://stackoverflow.com/questions/37640139/global-variable-value-in-case-of-fork

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!