我想添加钩子(Hook)函数,它会在共享库卸载时被调用。库在编译时链接。有可能做这样的事情吗?也许 gcc 有它的标志?
我看到类似的运行时加载库的解决方案,但它不符合我的期望。
最佳答案
对于 Linux 系统,dlopen()
/dlclose()
手册页解释了如何将这样的函数添加到您的库中:
Initialization and finalization functions
Shared objects may export functions using the
__attribute__((constructor))
and__attribute__((destructor))
function attributes. Constructor functions are executed beforedlopen()
returns, and destructor functions are executed beforedlclose()
returns. A shared object may export multiple constructors and destructors, and priorities can be associated with each function to determine the order in which they are executed. See the gcc info pages (under "Function attributes") for further information.An older method of (partially) achieving the same result is via the use of two special symbols recognized by the linker:
_init
and_fini
. If a dynamically loaded shared object exports a routine named_init()
, then that code is executed after loading a shared object, beforedlopen()
returns. If the shared object exports a routine named_fini()
, then that routine is called just before the object is unloaded. In this case, one must avoid linking against the system startup files, which contain default versions of these files; this can be done by using the gcc(1)-nostartfiles
command-line option.Use of
_init
and_fini
is now deprecated in favor of the aforementioned constructors and destructors, which among other advantages, permit multiple initialization and finalization functions to be defined.
关于linux - 共享库卸载的钩子(Hook)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52551525/