C Linux: Global variable located in shared library as singleton

后端 未结 3 1876
醉梦人生
醉梦人生 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)

    0 讨论(0)
  • 2021-02-15 17:05

    If a shared library (or a Windows DLL) is used by more than one process, any modifyable data is still private to the process. There are mechanisms like Copy on Write where the same data is shared as long as it is only read, but copied as soon as it is written by either process. So, for each process the data effectively is still separate. See also shared library address space.

    If you want to share data between processes, you need to use Shared Memory and make sure that access to the shared memory is synchronized between the processes.

    0 讨论(0)
  • 2021-02-15 17:16

    Processes each live in their own memory space. (Imagine the havoc you could wreak on a machine if you could, just by loading a library that some other process is using, completely arbitrarily trash their address space!) So, globals are global, but only within a process.

    0 讨论(0)
提交回复
热议问题