Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

202 Process Environment Chapter 7


Example


The program in Figure7.3 demonstrates the use of theatexitfunction.

#include "apue.h"

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

int
main(void)
{
if (atexit(my_exit2) != 0)
err_sys("can’t register my_exit2");

if (atexit(my_exit1) != 0)
err_sys("can’t register my_exit1");
if (atexit(my_exit1) != 0)
err_sys("can’t register my_exit1");

printf("main is done\n");
return(0);
}

static void
my_exit1(void)
{
printf("first exit handler\n");
}

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

Figure 7.3Example of exit handlers

Executing the program in Figure7.3 yields
$./a.out
main is done
first exit handler
first exit handler
second exit handler
An exit handler is called once for each time it is registered. In Figure7.3, the first exit
handler is registered twice, so it is called two times. Note that we don’t callexit;
instead, we return frommain.
Free download pdf