A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
atexit registers a function to be called when the program terminates normally via exit or return from main. You can register multiple handlers. They run in reverse registration order (last registered, first called). They receive no arguments and return void. They are the C equivalent of a destructor or a finally block. Use them for closing log files, releasing shared resources, writing final statistics, and cleaning up temporary files.
#include <stdio.h>#include <stdlib.h>void cleanup_first(void) {printf("Cleanup: first registered\n");}void cleanup_second(void) {printf("Cleanup: second registered\n");}void cleanup_third(void) {printf("Cleanup: third registered\n");}int main(void) {atexit(cleanup_first);atexit(cleanup_second);atexit(cleanup_third);printf("Main: doing work...\n");printf("Main: about to exit.\n");return 0;}
Reverse order. Third registered, first called. This is stack semantics: the last resource acquired is the first released. It mirrors the pattern of nested resource management: open A, open B, open C, then close C, close B, close A. atexit automates the closing half.
atexit handlers do not run if the program is killed by a signal (SIGKILL, SIGSEGV), if _exit is called instead of exit, or if abort is called. They run only on normal termination. If your cleanup is critical (flushing a write-ahead log, releasing a lock file), you may also need signal handlers. atexit covers the normal path. Signals cover the abnormal path.
Do not call exit from within an atexit handler. The behavior is undefined if a handler calls exit. If a handler needs to signal failure, set a global flag and let the normal exit path handle it. Also, the standard guarantees at least 32 registered handlers. Most implementations support far more, but 32 is the portable minimum.
atexit is the cleanup safety net. Register your handlers early, near the resource acquisition. They will run in the right order when the program exits normally. Next: abort, the abnormal termination function that skips cleanup and dumps core.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.