Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Linux: Global variable located in shared library as singleton

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, process 1 increments the var then proc2 increments the val and prints it.

My experiments so far showed that the both process keep copies of the variable and if 1st increments it the second will still read 0. So the behavior is not like Windows DLLs...

I read in one article here that if the global variable is not static (in the lib) and it's declared as extern in the lib header the var is unique for all the process. But so far I haven't been able to accomplish this - var is still copy for each process.

Can someone please offer good explanation of this? And how to do it...

like image 767
V0idd Avatar asked Jan 28 '13 13:01

V0idd


1 Answers

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.

like image 137
Andreas Fester Avatar answered Sep 18 '22 00:09

Andreas Fester