atexit函数

atexit函数

Section 7.3.  Process Termination

#include <stdlib.h>

int atexit(void (*func)(void));

Returns: 0 if OK, nonzero on error

ISO C一个进程最多注册32个可以自动被exit函数调用的函数。

传递一个函数指针做为atexit的参数,当该函数被调用时,不传递任何参数也不返回任何值。exit函数以这些函数的反向注册顺序执行。

ISO C和POSIX.1,exit函数先调用exit handler,然后再通过fclose关闭所有打开的流。POSIX.1 extends the ISO C standard by specifying that any exit handlers installed will be cleared if the program calls any of the exec family of functions。

Figure 7.3. Example of exit handlers
#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");
}
    $ ./a.out
    main is done
    first exit handler
    first exit handler
    second exit handler

发表评论