Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to call dlclose after dlsym

Tags:

c++

c

linux

macos

Coming from Windows I'm used to closing the handle to a DLL after getting a pointer to a symbol. Is this the same when using the dl functions? In the example below, will I still be able to use myFunction after dlclose is called? If not, does calling dlclose even matter?

void* handle = dlopen ("someLibrary", 0);
if (handle)
{
    myFunction = dlsym (handle, "MyFunction");
    dlclose (handle);
}
like image 621
Dave Avatar asked Sep 30 '14 22:09

Dave


1 Answers

dlclose closes the shared library (assuming it is the only reference to it), which means that the OS will unmap the shared library, and MyFunction is most likely no longer in memory.

Of course, if you do handle = dlopen("someLibrary", 0); handle2 = dlopen("someLibrary", 0);, then you can dlclose(handle); and the library is still "alive" because there is another reference (handle2) to it that is still alive.

It is of course not guaranteed that the OS unmaps it IMMEDIATELY, it may do that as a background process, so it MAY work to call it immediately after close, but not in 0.5 seconds time, or some such. There is no specification saying it must do one or the other, just that it is no longer valid to use

If you only ever open one library, use it throughout your program, then calling dlclose just before you exit is probably not essential, but if you open a lot of libraries (e.g. using some sort of plugin in a long-running program that can/will use many different plugins, the program may run out of virtual address space if you don't call dlclose.

(All shared libraries are closed on exit anyway, so leaving it open at exit should not be an issue)

like image 200
Mats Petersson Avatar answered Oct 06 '22 09:10

Mats Petersson