liveBook · Manning

Termination handler

As explained in Modern C, Third Edition

A termination handler is an application-supplied function executed as part of a program's termination processing.

A termination handler is an application-supplied function run during normal program termination. Register one with atexit by passing the function name, not a call: atexit(sayGoodBye). section 8.8

Logging termination

void sayGoodBye(void) { if (errno) perror("terminating with error condition"); fputs("Good Bye\n", stderr); } int main(void) { atexit(sayGoodBye); /* program work */ } After normal termination, sayGoodBye can free memory, write a termination timestamp, or report an error condition. section 8.8

int atexit(void func(void));
int at_quick_exit(void func(void));

Use the registration declarations to distinguish atexit from at_quick_exit and to see that each receives a function. section 8.8

Choose the termination path deliberately:

  • Use atexit for normal application cleanup. section 8.8
  • Use at_quick_exit with quick_exit for an alternative handler list when normal handlers are too time-consuming. section 8.8
  • Recognize that _Exit skips application handlers, while abort also inhibits some system cleanups. section 8.8

How Modern C, Third Edition covers it

How deep it goes
Defines registration and contrasts normal, quick, immediate, and abortive termination without detailing handler parameters.
Examples
Uses sayGoodBye to print a message, report errno, and illustrate cleanup or termination logging.
What it assumes
Assumes basic C functions and introduces function parameters as function references passed to atexit.
What you can do after
Operate/configure termination behavior by registering cleanup functions and selecting an appropriate exit function.
How it connects
Connects atexit with quick_exit, at_quick_exit, _Exit, abort, resource cleanup, and function pointers.

Related concepts

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