问题
Are there inherent dangers in using atexit in large projects such as libraries?
If so, what is it about the technical nature behind atexit that may lead to problems in larger projects?
回答1:
The main reason I would avoid using atexit in libraries is that any use of it involves global state. A good library should avoid having global state.
However, there are also other technical reasons:
Implementations are only required to support a small number (32, I think) of
atexithandlers. After that, it's possible that all calls toatexitfail, or that they succeed or fail depending on resource availability. Thus, you have to deal with what to do if you can't register youratexithandler, and there might not be any good way to proceed.Interaction of
atexitwithdlopenor other methods of loading libraries dynamically is not defined. A library which has registeredatexithandlers cannot safely be unloaded, and the ways different implementations deal with this situation can vary.Poorly written
atexithandlers could have interactions with one another, or just bad behaviors, that prevent the program from properly exiting. For instance, if anatexithandler attempts to obtain a lock that's held in another thread and that can't be released due to the state at the timeexitwas called.
回答2:
Secure CERT has an entry about atexit when not used correctly:
ENV32-C. All atexit handlers must return normally
https://www.securecoding.cert.org/confluence/display/seccode/ENV32-C.+All+atexit+handlers+must+return+normally
来源:https://stackoverflow.com/questions/17350308/atexit-considered-harmful