Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to call code upon termination in a C program?

Tags:

c

In C++ if I wish to have code called upon something bad happening I can place the code in the destructor, or a try-catch.

Is there a similar technique in C, whereby if the program terminates unexpectedly I can call a particular routine (to clean-up resources)?

like image 209
user997112 Avatar asked Jan 03 '23 22:01

user997112


1 Answers

In C, you use the C standard library function atexit, which allows you to specify a void function taking no parameters to be called when the program terminates (conceptually, when the closing brace } of the first calling of main is reached).

You can register up to 32 such functions in portable C and they are called in the reverse order in which they were registered.

See http://en.cppreference.com/w/c/program/atexit

like image 80
Bathsheba Avatar answered Jan 05 '23 16:01

Bathsheba