Example

This example demonstrates the use of the atexit function. The main program first installs three exit handlers:

    if (atexit(my_exit1) != 0)
	err_sys("can't register my_exit1");
    if (atexit(my_exit2) != 0)
	err_sys("can't register my_exit2");
    if (atexit(my_exit1) != 0)
	err_sys("can't register my_exit1");
It then prints a message and exits:
    printf("main is done\n");
The exit is conditional. If there are no command line options, the main program returns 0. If there are any command line options and the first option starts with 'x', then _Exit(2) is called otherwise exit(3) is called:
    if (argc>1) {
	if (argv[1][0]=='x') _Exit(2);
	else exit(3);
    }
    return(0);

Execution

Executing the program with no command options yields

$ ./doatexit
main is done
first exit handler
second exit handler
first exit handler
$ echo $?
0
An exit handler is called once for each time it is registers. The reader may wish to change the order in which the handlers are registered to check that they are called in "last in, first out" order.

The command echo $? echoes the status value.

Executing the program with command option y yields:

$ ./doatexit y
main is done
first exit handler
second exit handler
first exit handler
$ echo $?
3
The result is the same except that the status is 3.

Executing the program with command option x yields:

$ ./doatexit x
main is done
$ echo $?
2
The exit handlers were NOT called and the status is 2.

Source for doatexit.c

#include	<stdio.h>
#include	<stdlib.h>

static void	my_exit1(void), my_exit2(void);

static void err_sys(char *str)
{
	perror(str);
	exit(1);
}

int main(int argc, char *argv[])
{
	if (atexit(my_exit1) != 0)
		err_sys("can't register my_exit1");
	if (atexit(my_exit2) != 0)
		err_sys("can't register my_exit2");
	if (atexit(my_exit1) != 0)
		err_sys("can't register my_exit1");
	printf("main is done\n");
	if (argc>1) {
		if (argv[1][0]=='x') _Exit(2);
		else exit(3);
	}
	return(0);
}
static void my_exit1(void)
{
	printf("first exit handler\n");
}

static void my_exit2(void)
{
	printf("second exit handler\n");
}


Maintained by John Loomis, last updated 22 August 2006