问题
There are several tutorials which explains the usage of atexit() function such as:
http://linux.die.net/man/3/atexit
The examples are given in a main function which can be understood easily. However, I am creating a shared library in my program and I provide some functions to be exported from other programs. I want to stop some threads inside shared library when another program unloads my shared library. How can I use atexit() in my shared library implementation without forcing users to call some function e.g. destroy() at the end?
Thanks in advance.
回答1:
The documentation states:
Since glibc 2.2.3, atexit() (and on_exit(3)) can be used within a shared library to establish functions that are called when the shared library is unloaded.
On the other hand, why don't you just make an object of global scope and perform your tidy up code in its destructor?
回答2:
You should avoid doing so (unless you really must for some really strong reason).
The lib should just provide functions and let the app the liberty how to use it. If your library exports a function which start some helper thread(s), provide also a function to stop it and document it appropriately. Keep on the app's responsibility to free resources it allocated.
If it is some your idea to fix buggy programs which do call some lib_init() but forget lib_uninit(), then forget it. It will make you lib much more complex and you can never fix all potential bugs the app. programmer can create, and debugging such application will be then harder.
IMHO, libraries should (as far as possible) avoid changing some global process stuff because such libraries cause limitations how the application can be designed. Such libraries are nightmare, especially if you link with multiple ones and they have contradictory assumptions how the application should be written.
来源:https://stackoverflow.com/questions/10702980/atexit-function