C Linux: Global variable located in shared library as singleton

后端 未结 3 1885
醉梦人生
醉梦人生 2021-02-15 16:43

Is it possible to use global variable located in a shared library (.so) as a singleton if the library is used by more than one process?

As example the initial value is 0

3条回答
  •  野的像风
    2021-02-15 16:59

    Linux does not support sharing of global variables that are laid out by the linker. That memory will be in unsharable space.

    If you only want to share the data with and among descendent processes (and not with arbitrary processes that are started up seperately, that just happen to link to the same shared library), then the easiest way to do this is have the library create a mapping with mmap() in a constructor function (that is called when the library is initially loaded in the parent process).

    Pass the MAP_ANONYMOUS and MAP_SHARED flags to mmap - this will mean that child processes that inherit the mapping will have a mapping that is shared with the parent (and the other children)

提交回复
热议问题