【问题标题】:Will dlopen yield the same handle for two calls with the same file?dlopen 会为具有相同文件的两个调用产生相同的句柄吗?
【发布时间】:2012-08-27 19:37:30
【问题描述】:

如果我在同一个应用程序运行中对同一个库/文件使用 dlopen 两次,它会在两种情况下产生相同的句柄吗?对此有什么保证吗(一个简短的实验表明它至少在我的盒子上是这样)?

我目前正在玩一个小插件系统(出于好奇),如果对这种观察到的行为有某种保证,我可以使用这个地址作为插件的密钥,以防止重复加载。

【问题讨论】:

    标签: c linux plugins shared-libraries


    【解决方案1】:

    是的。 dlopen(3) linux 手册页说:

       If the same library is loaded again with dlopen(), the same file 
       handle is returned. The dl library maintains reference counts for 
       library handles, so a dynamic library is not deallocated until 
       dlclose() has been called on it as many times as dlopen() 
       has succeeded on it.
    

    顺便说一句,在 Linux 系统上,您可以 dlopen 很多(几十万个)共享库,正如我的示例 manydl.c 所示。主要限制是地址空间。 所以实际上,不用理会dlclose-ing 的东西是可能的。

    (除非你的 dlopen 共享库有奇怪或消耗资源的构造函数或析构函数)

    2017 年 12 月添加:

    请注意,相关的是传递给dlopen 的确切路径字符串。因此,如果您使用"./foo.so""././foo.so"(或"../foosymlink.so",其中foosymlink.sofoo.so 的符号链接),dlopen-ed 句柄是不同的,在某些情况下,该共享库的两个实例的行为会很奇怪可能发生。

    2019 年 6 月添加:

    另请阅读 Drepper 的 How to write shared libraries 论文(它还很好地解释了如何使用它们!)。

    【讨论】:

    • .. 我刚刚阅读了这个手册页,为什么我没有阅读这一段呢? Hmpf ..好吧,仍然感谢您回答我的愚蠢问题:)
    • 可能有必要提到每个连续的dlopen 都会增加引用计数,因此插件在dlclosed 匹配的次数之前不会被卸载。
    • "请注意,相关的是传递给 dlopen 的确切路径字符串。"一般情况下好像不是这样。我刚刚在 macOS 上进行了测试,当使用不同的路径、符号链接,甚至复制文件时,它仍然返回相同的句柄。当我修补 LC_ID_DYLIB 时,它确实返回了一个不同的句柄。
    猜你喜欢
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2012-05-26
    相关资源
    最近更新 更多