Sharing same variable between more than one independent programs in Linux [closed]

Variables you declare in your headers will generate a copy where ever you include them (unless you declare them extern). Of course, when dealing with separate processes every process will have its own memory space. You need to use more sophisticated techniques to circumvent this, i.e. Inter Process Communication (IPC). For example:

  • (named) Pipes
  • Sockets
  • Shared Memory

Your question reads like shared memory is what you want, since hereby multiple processes can access the same memory regions to share some variables. Maybe take a look at this question and its answers for an example.

Your program would be required to create some shared memory, e.g. using shmget and to attach the shared memory object using shmat.
When multiple processes access same memory regions, it’s always a healthy approach to add process synchronization during read/write on the variable, e.g. using a shared semaphore (semget, semop).

When you are done with your shared memory you need to detach (shmdt) from it. Thereby you tell the kernel that your process no longer needs access to it.
The process that created the shared memory/semaphore object also needs to destroy them at the end of your program(s). Otherwise it will reside in memory, probably until you reboot your machine (see shmctl, semctl, especially IPC_RMID).

Note that for shared memory objects “The segment will only actually be destroyed after the last process detaches it”. So you want to make sure, that this actually happens for all of your processes (shmdt).


In response to the comments, here is the POSIX approach:

System V shared memory (shmget(2), shmop(2), etc.) is an older shared memory API. POSIX shared memory provides a simpler, and better designed interface; on the other hand POSIX shared memory is somewhat less widely available (especially on older systems) than System V shared memory.

See also this overview and here for examples.

Finally, note that

POSIX shared memory objects have kernel persistence: a shared memory object will exist until the system is shut down, or until all processes have unmapped the object and it has been deleted with shm_unlink(3)


In order to take into account the persistence of the shared memory objects, don’t forget to add signal handlers to your application that will perform the clean up operations in case of an exceptional termination (SIGINT, SIGTERM etc.).

Leave a Comment