挂钩函数可共享库卸载 [英] Hook function to shared library unloading
问题描述
我想添加挂钩函数,该函数将在共享库卸载时调用。图书馆链接紧密联系。有可能这样做吗?也许海湾合作委员会有标志吗?
I want to add hook function, which will be called when shared library is unloaded. Library is linked on complitaion. Is it possible to do such thing? Maybe gcc has flag for it?
我看到了类似的在运行时加载库的解决方案,但它没有达到我的期望。
I saw similar solution for loading library on runtime, but it doesn't meet my expectations.
推荐答案
对于Linux系统, dlopen()
/ dlclose()
手册页介绍了如何在您的库中添加这样的功能:
For Linux systems, the dlopen()
/dlclose()
man page explains how to add such a function to your library:
初始化和终结函数
共享对象可以使用
__ attribute __((constructor))
和
__ attribute __((destructor))
函数属性。构造函数在dlopen()
返回之前执行,析构函数
函数在dlclose()
返回之前执行。共享对象可以
导出多个构造函数和析构函数,并且优先级可以是与每个函数关联的
以确定执行它们的
顺序。有关更多信息,请参见gcc信息页面(在函数属性下)。
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.
(部分)实现相同结果的较旧方法是通过
的使用链接器识别的两个特殊符号中的一个: _init
和
_fini
。如果动态加载的共享库导出名为 _init()
的例程,则该代码将在加载共享的
对象之后,在 dlopen之前执行。 ()
返回。如果共享库导出了名为 _fini()
的
例程,则该例程将在
对象卸载之前被调用。在这种情况下,必须避免链接到
系统启动文件,该文件包含这些文件的默认版本;
这可以通过使用gcc(1) -nostartfiles
命令行
选项来完成。
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, before dlopen()
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.
现在不建议使用 _init
和 _fini
,而推荐使用上述
的构造函数和析构函数,它具有
的其他优点,其中允许定义
多个初始化和终结功能。
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.
这篇关于挂钩函数可共享库卸载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!