But when you dlclose, and then dlopen again, it doesn't initialise globals or statics the second time.
This is most likely happening because the library was in fact not unloaded on dlclose
.
From man dlclose
The function dlclose() decrements the reference count on the dynamic library
handle handle. If the reference count drops to zero and no other loaded
libraries use symbols in it, then the dynamic library is unloaded.
It is most likely that you didn't satisfy "no other loaded libraries use symbols in it" part.
You can run the binary with LD_DEBUG=symbols,bindings
and watch for messages like this:
binding file XXX to libYYY.so: normal symbol `ZZZ'
If you bind any symbols in libYYY.so
to a file that is not unloaded, then libYYY.so
can't be unloaded on dlclose
.