Tuesday 8 November 2011

Is it possible to execute code even after the program exits the main() function? in C programming

Is it possible to execute code even after the program exits the main() function?

The standard C library provides a function named atexit() that can be used to perform “cleanup” operations when your program terminates. You can set up a set of functions you want to perform automatically when your program exits by passing function pointers to the atexit() function. Here’s an
example of a program that uses the atexit() function:

#include <stdio.h>
#include <stdlib.h>
void close_files(void);
void print_registration_message(void);
int main(int, char**);
int main(int argc, char** argv)
{
atexit(print_registration_message);
atexit(close_files);
while (rec_count < max_records)
{
process_one_record();
}
exit(0);
}
This example program uses the atexit() function to signify that the close_files() function and the
print_registration_message() function need to be called automatically when the program exits. When the
main() function ends, these two functions will be called to close the files and print the registration message.
There are two things that should be noted regarding the atexit() function. First, the functions you specify
to execute at program termination must be declared as void functions that take no parameters. Second, the
functions you designate with the atexit() function are stacked in the order in which they are called with
atexit(), and therefore they are executed in a last-in, first-out (LIFO) method. Keep this information in
mind when using the atexit() function. In the preceding example, the atexit() function is stacked as
shown here:

atexit(print_registration_message);
atexit(close_files);
Because the LIFO method is used, the close_files() function will be called first, and then the
print_registration_message() function will be called.

The atexit() function can come in handy when you want to ensure that certain functions (such as closing
your program’s data files) are performed before your program terminates.

Cross Reference:

VIII.9: Is using exit() the same as using return?

No comments:

Post a Comment