Alex Rivera | Logout

linux dlopen: can a library be "notified" when it is loaded?

Asked 2009-10-21T17:42:43.740
13

Is there a way for a shared library to be "notified" when it is loaded?

In other words, let's say I use dlopen on a shared library, is there a function that is automatically called (if present) on the shared library (e.g. main?)

Edit
Report

1 Answer

17

Yes. When a library is opened, all static construction takes place... so, if you use C++, you can do:

// mylibrary.cpp
namespace
{
    class dynamic_library_load_unload_handler
    {
         public:
              dynamic_library_load_unload_handler(){
                    // Code to execute when the library is loaded
              }
              ~dynamic_library_load_unload_handler(){
                    // Code to execute when the library is unloaded
              }
    } dynamic_library_load_unload_handler_hook;
}

Unlike the __attribute__ ((constructor)) solutions given, this will be portable. Note, though, that if you have multiple objects like this, there is no guarantee with respect to the construction/destruction order.

answered 2009-10-21T20:29:10.910

Your Answer