I know that atexit is used to register a function handler. Then when an exit in the code occur that function is called. But what if an exit occur inside the function handler?
I was expecting an infinite loop but in reality the program exit normally. Why?
void handler(){
printf("exit\n");
exit(1);
}
int maint(int argc, char *argv[]) {
atexit(handler);
exit(1);
}
The behavior is undefined.
7.22.4.4 The exit function
2 The exit function causes normal program termination to occur. No functions registered by the at_quick_exit function are called. If a program calls the exit function more than once, or calls the quick_exit function in addition to the exit function, the behavior is undefined.
Calling exit
in an at_exit
handler (that is being run during the normal processing of exit) is definitely a second call to exit.
Exiting normally is a possible behavior, but seeing as anything can happen (the nature of the behavior being undefined), it could very well result in catastrophe. Best not to do it.
(Calling
exit
in anat_exit
handler is definitely a second call toexit
if the handler was called due toexit
being called, but a handler may be called by the program normally, in which case it would be the firstexit
call. But then it would be called again, unless the handler took a different code path.)@EricPostpischil ok, but why it doesn't create an infinite loop? The behavior is undefined, so it can create loop or, as in this case, not create it?
Undefined means undefined. It could do anything, and it is meaningless to ask of the standard why a particular thing did or did not happen. You can only ask why your implementation did a particular thing, and the answer is almost always "because it did".