In a shared library, a function func1() has atexit(terminate_global) and this shared library don't have 'attribute ((constructor))' and 'attribute ((destructor))'.
So, the program flow is like below:
1) Application loads shared lib using dlopen.
2) Applications calls func1() using dlsym.
3) func1() has atexit(terminate_global).
4) func1() returns.
5) Application calls dlclose to de-allocate the library.
In above steps I don't find the atexit() been called when the library was unloaded. So, what should be the correct way if the atexit() has to be called when we de-allocate the shared library? Should I export routines using the attribute((constructor)) and attribute((destructor)) function attributes so as atexit registered function can be called?
I assume that the terminate_global
function passed to atexit
is defined in the plugin. If terminate_global
is a global function defined by the main program (linked with -rdynamic
flag, to get its symbols accessing to plugins) then a plugin could call atexit(terminate_global)
, but then I would provide some API function doing that.
I won't do that (calling atexit(terminate_fun)
inside some plugin where terminate_fun
is a function defined by the plugin), unless you are sure that your application is never dlclose
-ing the plugin.
If your application is somewhere calling dlclose
-outside of some atexit
-ing function- that dlclose
is likely to munmap
the plugin.so
and when later exit
is processing atexit
it will crash (since the pointer to the function registered thru atexit
is invalid and unmmapped)
You have to define who is in charge of dlclose
-ing the plugin. If your application is explicitly doing that, you either could have some cleanup done by a __attribute__((destructor))
C function (or the destructor of some static C++ data in the plugin), or define and document a convention telling e.g. that every plugin which has a function named plugin_cleanup
(that you would get with dlsym
) would have that cleanup function called appropriately.
You could otherwise define and document that plugins are not explicitly dlclose
-d by your application (this is often OK, in particular if you offer some cleanup machinery). However, that may make valgrind
unhappy.