Register Exit Handlers with atexit and on_exit
atexit registers cleanup functions that run in reverse order when a program ends normally. on_exit also passes the status. Neither runs after _exit or abort.

A C program often owns something that must be released on the way out: a temporary file to delete, a lock file to remove, a terminal to put back into cooked mode, a log buffer to flush. Putting that cleanup at the end of main() misses every other way the program can leave, such as an exit() call deep inside a helper or a return from an error path. The C library gives you a cleaner tool: register a function once, and the library calls it whenever the program ends normally. This post covers atexit(), the glibc extension on_exit() that also receives the exit status, the order handlers run in, the exits that skip them and the few rules a handler must follow. It uses C17, GCC 14 and glibc 2.40 on Linux 6.12, and follows atexit(3), on_exit(3) and the C standard.
atexit in one program
#include <stdlib.h>
int atexit(void (*function)(void));atexit() takes a function with no parameters and no return value and registers it. It returns 0 on success and a nonzero value on failure (typically no memory left in the registration table). The function runs when the program ends through exit() or by returning from main().
#include <stdio.h>
#include <stdlib.h>
static void say_goodbye(void)
{
puts("cleanup: goodbye");
}
int main(void)
{
if (atexit(say_goodbye) != 0) {
fputs("could not register handler\n", stderr);
return EXIT_FAILURE;
}
puts("main: working");
return EXIT_SUCCESS;
}main: working
cleanup: goodbyeThe handler ran after main() returned, because returning from main() is equivalent to calling exit(). Calling exit() from anywhere else would run it too, which is the benefit: the cleanup lives next to the resource, not at every exit point.
Reverse order
Handlers run in the reverse order of registration, last in, first out, like destructors. That is the correct order for dependent resources: register the cleanup for a resource right after you acquire it, and they unwind in the right sequence.
#include <stdio.h>
#include <stdlib.h>
static void close_log(void) { puts("closing log file"); }
static void remove_lock(void) { puts("removing lock file"); }
static void restore_term(void) { puts("restoring terminal"); }
int main(void)
{
puts("creating lock file");
atexit(remove_lock);
puts("opening log file");
atexit(close_log);
puts("switching terminal to raw mode");
atexit(restore_term);
puts("main done");
return 0;
}creating lock file
opening log file
switching terminal to raw mode
main done
restoring terminal
closing log file
removing lock fileThe terminal, set up last, is restored first. If the order were forward, the lock file would be removed while the log file was still open, which for resources that depend on each other can fail. The standard guarantees support for at least 32 registered functions; glibc has no fixed limit and grows its table as needed.
on_exit, the glibc extension
on_exit() is a variant that is not in the C standard or POSIX but exists in glibc and some other libraries. Its handler receives the exit status and a user pointer, which makes cleanup context-aware without globals:
#include <stdlib.h>
int on_exit(void (*function)(int status, void *arg), void *arg);#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
struct job {
const char *name;
int started;
};
static void finish(int status, void *arg)
{
struct job *job = arg;
printf("job %s: exiting with status %d, started=%d\n",
job->name, status, job->started);
}
int main(void)
{
static struct job nightly = { "nightly-backup", 1 };
on_exit(finish, &nightly);
puts("running job");
exit(3);
}running job
job nightly-backup: exiting with status 3, started=1The status passed is the argument to exit() or the value returned from main(). The arg pointer must remain valid until exit, so it points at a static object here; a pointer to a stack variable of a function that has already returned is the same bug as in putenv(). Note the feature test macro: without _DEFAULT_SOURCE, strict C17 mode hides the declaration. Because on_exit() is not portable, use it only in code that is glibc-specific, or hold the data in a file-scope variable and use atexit() instead. The on_exit(3) man page advises avoiding it in favor of atexit(), so for new code that must be portable, prefer the latter.
What does not run the handlers
Handlers run only on a normal exit. Several ways to leave skip them entirely:
| How the process ends | Handlers run? |
|---|---|
return from main() | yes |
exit() | yes |
_exit() or _Exit() | no |
abort() | no |
Killed by a signal such as SIGKILL or an unhandled SIGSEGV | no |
quick_exit() | no (only at_quick_exit handlers) |
execve() | no: the whole process image is replaced |
A fork() child that calls _exit() | no |
Two of these deserve a note. After fork(), the child inherits the parent's registered handlers. If the child calls exit() instead of _exit(), it runs them, which can delete the parent's temporary files or flush its buffers a second time; that is why a child that is only going to exec should call _exit() on failure. And execve() discards the registrations along with the old program, which is correct and expected.
A signal that kills the process also skips handlers, so cleanup that must survive a crash (removing a stale socket file, for instance) needs another mechanism: handle SIGTERM and SIGINT by setting a flag so that the program returns normally, or design the resource so that a leftover is harmless.
Rules for handlers
A handler runs in the middle of exit(), in a state where the program has finished but the process has not. A short list of rules keeps it safe:
**Do not call
exit()from a handler.** The result is undefined. To change the exit status in a handler, call_exit().**Do not call
longjmp()out of a handler.** The behavior is undefined, and glibc cannot unwind through its own exit machinery.Keep handlers short and self-contained. They should not depend on resources another handler already released, which the reverse order mostly protects against.
Do not register handlers while exiting unless you understand the effect: a handler registered during exit runs, in the order specified for newly registered functions, but the rules are subtle.
Be careful with threads. Handlers run on the thread that called
exit(), while other threads may still be running and using the resource you are about to free. Shut worker threads down before exiting, or make the cleanup tolerate them.
Flushing, and what the library already does
exit() flushes and closes every open stdio stream after running the handlers, so you do not need a handler for fflush() on streams opened with fopen(). You do need your own code for resources the library does not know about: files opened with open() and written with raw write(), buffers you manage yourself and anything stored outside the process, such as a lock file or a shared memory segment name. A cleanup handler that calls unlink() on a temporary file is the standard example:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static char tmp_path[] = "/tmp/report-XXXXXX";
static void remove_tmp(void)
{
if (unlink(tmp_path) == 0)
printf("removed %s\n", tmp_path);
}
int main(void)
{
int fd = mkstemp(tmp_path);
if (fd == -1) {
perror("mkstemp");
return EXIT_FAILURE;
}
atexit(remove_tmp);
dprintf(fd, "scratch data\n");
close(fd);
puts("working with the temporary file");
return EXIT_SUCCESS;
}working with the temporary file
removed /tmp/report-k3Jf9aThe six characters at the end of the file name are random and will differ on every run. The handler removes the file whether main() returns normally or some helper calls exit(1) after an error, which is exactly the behavior you want from a cleanup hook.
Handlers and shared libraries
Each shared library can register its own handlers, and glibc runs them in the same reverse order as the rest. When a library is unloaded with dlclose(), the handlers it registered through atexit() are removed first, so they do not run after the code they point to has been unmapped. A library should register handlers with atexit() from its constructor only if it truly needs them at process exit; the more robust way for a shared object is __attribute__((destructor)), which also runs at dlclose() time. The posts on constructors and on exit variants pick this up.
Testing a handler
Because a handler runs during exit(), test it by running the program and checking its side effects after it ends: the temporary file is gone, the lock file is removed, the log line was written. A small shell script does it: run the program, then test ! -e /tmp/report-*, and run it again with a path that makes it fail early, to confirm the cleanup also runs when the program exits through an error branch that calls exit(1). Test the _exit() and SIGKILL cases too, in the other direction: assert that cleanup does not run, and make sure the design tolerates the leftover, for example by having the next start remove a stale file.


