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