Tuesday, October 29, 2013

Global Variables in Shared Objects

I believe, even people are smart enough, capable enough to do more challenging tasks, they wont get opportunities. 

Recently, Because os some recent analysis of some issues. I came across one issue which made me to understand one of the good concepts of Shared Libraries in real world scenario. Even it is small but should know and understand.

One of the middleware processes and another application process shared the same library though which both can access one of the Shared Memory database. Timer was running in the middleware process to update one global counter variable in the library. It was updating and printing the values properly. 

Due to one of the issues reported by the client, we found that that counter variable needs to be reset upon one of the request from GUI. Recipient for the GUI request is Application. Hence, as application also shared the same library, we thought to reset the counter from application.  But when we did the same and print the value, counter was resetting properly. Next time, when timer started from middleware and prints the value, then it was continued from the previous value of the counter variable. This mean, resetting was not successful but we were getting proper value at application. 



After we found that, as this is shared library between application process and middleware process, global variables of shared objects will have different copy for each process. That is the reason behind using shared memory database in our project. Even SMDB is used, library to access the SMDB component is just shared object, ideally, which should not have global variables. In other words, global data will run in process address space I believe and hence each process will have its own copy. 

After few Googling, found following points are important.

1. If a shared library uses a global variable that is not exported, each process that uses that library get a copy of that variable -  Data is specific to processes, not libraries.

2. Only CODE is shared, not data (well, constant data might be shared) 

If any of you have more information or good links related to this, drop here as your comments.

Thanks in advance...