4

如果通过 dlopen 和 dlclose 机制使用共享库(或 DLL),并且如果创建的共享库有一些全局变量,其内存来自堆,那么调用 dlclose 时这些变量和内存会发生什么?

如果在同一进程中,再次调用 dlopen,会是什么行为?

4

1 回答 1

8

If dlclose reduces the reference count to zero and the library is actually unloaded, any future reloading of the library should reset all variables with static storage duration in the library to their original values.

However, if the library was opened more than once, all but the final call to dlclose will just decrement the reference count. Sometimes it may not be obvious whether a library was opened more than once, since it might have gotten loaded as a dependency of some other library without you knowing, unless it's a module local to your program, so it's probably not a good idea to rely on this "reset" behavior.

Employed Russian added:

Even if the library is dlopen()ed and dlclose()d exactly once, and is not a dependency of something else, the act of referencing symbols from it (via dlsym()) will also increment the reference count (and make the library not unloadable); at least on Linux.

I have no idea if this information is accurate or not. In the future, please post new information as a comment or a new answer, not an edit to other people's answers. If you just edit someone else's answers, you make them take responsibility for the correctness of your answer, which they may not want.

于 2011-01-19T06:43:38.977 回答