// g++ -ldl -o test_dlopen test_dlopen.c && ./test_dlopen ./libtest.so #include #include #include #include int cb(struct dl_phdr_info* info, size_t size, void* data) { std::cout << info->dlpi_name << std::endl; return 0; } typedef void (*test_fct)(); int main(int argc, char** argv) { const char* szLibPath = "./libtest.so"; if ( argc > 1 ) { szLibPath = argv[1]; } // dlopen the library and list all loaded libraries in memory void* pLibHandle = dlopen(szLibPath, RTLD_LAZY|RTLD_GLOBAL); std::cout << "-----------------------------------------------------------------------------------" << std::endl; std::cout << "Loaded libraries, after " << szLibPath << " has been loaded" << std::endl; dl_iterate_phdr(cb, 0); // dlclose the library and list again all closed libraries std::cout << "-----------------------------------------------------------------------------------" << std::endl; std::cout << "dlclose(pLibHandle) return value: " << dlclose(pLibHandle) << " (should return 0)" << std::endl; // should return 0 std::cout << "Loaded libraries after " << szLibPath << " has been closed..." << std::endl; dl_iterate_phdr(cb, 0); // the bug is here really visible, since a second dlcolse(pLibHandle) returns 0 although the library has been closed already std::cout << "-----------------------------------------------------------------------------------" << std::endl; std::cout << "dlclose(pLibHandle) return value: " << dlclose(pLibHandle) << " (should return -1)" << std::endl; // should return -1 return 0; }