How to share global variables in a shared library(.so) across instances of the same process that use the shared library in Linux?

linux, shared-libraries

Solution

To phrase this most clearly: you cannot do exactly what you asked. Linux does not support sharing of global variables that are laid out by the linker. That memory will be in unsharable mapped-to-swap space.

A general recipe I can offer is this:

- define a struct that lays out your data. No Pointers! Just offsets.

- first process creates a file in /tmp, sets access rw as needed. Open, mmap with MAP_SHARED.

- Subsequent processes also open, mmap with MAP_SHARED.

- everybody uses the struct to find the pieces they reference, read, or write.

- Look Out For Concurrency!

If you really only care about a parent and it's forked children, you can use an anonymous mapping and not bother with the file, and you can store the location of the mapping in a global (which can be read in the children).

Problem

I have a shared library(.so) that I preload before executing an application and I have a few global data structures in the shared library that the application uses. The application can create other processes say using fork() and these processes can update the global data structures in the shared library. I would like to keep a consistent view of these global data structures across all the processes. Is there any way I can accomplish this in Linux? I have tried using shm_* calls and mmap() to map the global data of the shared library to a shared segment but it does not work.

Original source