dlopen会为同一个文件的两个调用产生相同的句柄吗?

mag*_*eta 7 c linux plugins shared-libraries

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

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

Bas*_*tch 13

是.该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.
Run Code Online (Sandbox Code Playgroud)

顺便说一下,在Linux系统上,你可以使用很多(数十万)共享库,正如我的示例manydl.c所示.主要限制是地址空间.所以实际上,不需要打扰dlclose东西也是可能的.

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

2017年12月新增:

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