问题
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:
Why does being 'forked' change the basic method of memory update for this variable? I thought that global variable has a specific memory mapping
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