Warm tip: This article is reproduced from stackoverflow.com, please click
c

What happen if an exit occur inside the atexit handler?

发布于 2020-03-27 10:31:22

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);
}
Questioner
Mattia Corradi
Viewed
101
StoryTeller - Unslander Monica 2019-07-02 20:07

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.