dlclose gets implicitly called

前提是你 提交于 2020-01-11 13:09:31

问题


So I was studying about shared libraries and I read that an implicit dlclose() is performed upon process termination. I want to know who is responsible for this call. For example, if I wrote:

#include <stdio.h>

int main() {
        printf("Hello World\n");
        return 0;
}

And then if I did ldd ./a.out then I get a list of these libraries:

linux-vdso.so.1 =>  (0x00007ffd6675c000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f2569866000)
/lib64/ld-linux-x86-64.so.2 (0x0000562b69162000)

Linker is responsible for loading these right, so who is responsible upon termination of this ./a.out executable for implicit dlclose() of these libraries?


回答1:


I do not have Kerrisk's book, but if you have accurately characterized its contents then they seem to be a bit simplified. It is not strictly correct to say that whenever a process terminates, the function dlclose() is called for each of its open shared libraries, but it is reasonable to say that whenever a process terminates, all its handles on open shared libraries are closed. As a result, the operating system recognizes that one fewer process references each of those shared libraries, and if that brings any shared libraries' reference counts to zero then the OS may choose to unload them from memory.

dlclose() does more work than that. In particular, it causes any destructor functions in the library to run. Those functions will also run when the process exits normally by returning from main() or by calling exit(), but not if the process terminates by other means, such as calling _exit() or in response to receiving a signal. In the normal-exit case, the net effect may be the same as if dlclose() were called for each open shared library, but even then, that's not necessarily achieved by actually calling dlclose().

Finally, do be aware that although the dl*() functions are defined by POSIX, substantially all details of dynamic / shared libraries are left at the discretion of implementations. Since you've asked about a Linux book, I've referenced a few Linux-specific details.




回答2:


I suspect the book is only talking about normal process termination when calling exit() or returning from main(). dlopen() presumably registers an atexit() handler that executes all the termination functions of the dynamic libraries.

It's not feasible for libraries to execute any code when a process is terminated abnormally. If the process is terminated by the OS instead of by exiting normally, the OS just releases any file handles, but it won't execute code in the context of the process.



来源:https://stackoverflow.com/questions/41110448/dlclose-gets-implicitly-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!