Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to find out the number of references to a dynamic library in a process?

Tags:

c

linux

dlopen

Is there a way to find out the number of references to a dynamic library in a process? i.e. in an application many modules might have loaded the same library using dlopen and when a module does dlclose, can we know if the library is really being unloaded or it's reference is just being decremented?

like image 624
Jay Avatar asked Nov 07 '11 06:11

Jay


1 Answers

From the man page:

dlclose()

The function dlclose() decrements the reference count on the dynamic library handle handle. If the reference count drops to zero and no other loaded libraries use symbols in it, then the dynamic library is unloaded.
The function dlclose() returns 0 on success, and nonzero on error.

So reference counting is done automatically, but the fact that this call is the last one and does unload the library is not indicated. You'll need to count yourself if you need that.

Or you could dlopen with the RTLD_NOLOAD after the dlclose:

Don't  load  the  library.   This  can  be  used  to  test if the library is already resident  (dlopen() returns NULL if it is not, or the library's handle if it is resident).

(Note that you'll need to dlclose() it again if you got a reference. This is racy, so make sure all the potential manipulations happen in a single thread or are serialized.)

You might be interested in the RTLD_NODELETE option:

Do not unload the library during dlclose(). Consequently, the library's static variables are not reinitialized if the library is reloaded with dlopen() at a later time. This flag is not specified in POSIX.1-2001.

like image 200
Mat Avatar answered Sep 20 '22 12:09

Mat