liveBook · Manning

Atexit

As explained in Modern C

atexit is the C standard library function that registers a function to be called during normal program termination.

atexit registers a function to run during normal program termination. The registration passes the function itself, so write atexit(sayGoodBye), not atexit(sayGoodBye()). section 8.7

Registering a termination handler

void sayGoodBye(void) { if (errno) perror("terminating with error condition"); fputs("Good Bye\n", stderr); } int main(int argc, char* argv[argc+1]) { atexit(sayGoodBye); ... } After normal termination, sayGoodBye reports the status and can perform cleanup such as freeing memory or writing a timestamp. section 8.7

Use termination handlers with these constraints:

  • Prefer ordinary exit and preserve library cleanup unless bypassing it is necessary. section 8.7
  • Use quick_exit and at_quick_exit only when the normal handler list is too time-consuming. section 8.7

How Modern C covers it

How deep it goes
Defines registration syntax and behavior through one example, but defers detailed function-parameter mechanics.
Examples
Uses a sayGoodBye handler that checks errno, reports errors, writes to stderr, and represents cleanup work.
What it assumes
Assumes basic C functions and termination concepts while deferring function-pointer terminology and mechanics.
What you can do after
Apply it by registering a no-argument handler for cleanup or status reporting during normal termination.
How it connects
Connects normal program termination with exit, library cleanup, function pointers, quick_exit, and at_quick_exit.

Also explained in

Compare how 2 books explain atexit →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.