I want to share a variable between more than one independent C executables in Linux. That is, a program will write on an array and set a flag so that no other program can use it, and after this operation it’ll unset the flag and then another program will read the array. I tried using the same custom header file (containing the variable) in every program, but it seems different instances of the variables are created when the programs are invoked.
Share
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: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:
See also this overview and here for examples.
Finally, note that
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.).