ISO C中,一个进程可以注册32个由exit自动调用的函数。这被称为exit handlers,可以通过调用atexit来注册。
atexit - register a function to be called at normal process termination
#include <stdlib.h>
int atexit(void (*function)(void));
//Returns: 0 if OK, nonzero on error
参数是需要注册的函数地址
注意点:
- 通过atexit注册的函数调用的时候,不传递任何参数,也不返回任何值
exit
调用这些函数的顺序,依照注册时候的相反顺序- 每个函数被注册了几次就调用几次
- POSIX.1 扩展了ISO C标准,规定进程调用了任何
exec
系统调用,就会清除任何已安装的exit handlers
exit handler
是ANSI C Standard在1989年提出的
ISO C需要系统支持至少32个exit handlers
通过sysconf
可以来决定给定平台支持的exit handlers
的最大数量
图例演示:
我们知道,进程自愿终止的方法只有三种: _exit,_Exit and exit
不自愿的终止方法: signal(信号)
此外,内核执行程序的唯一方法就是调用exec
Example:演示atexit的使用
#include "apue.h"
static void my_exit1(void);
static void my_exit2(void);
int main(void)
{
if (atexit(my_exit2) != 0) //注册exit2
err_sys("can’t register my_exit2");
if (atexit(my_exit1) != 0) //注册exit1
err_sys("can’t register my_exit1");
if (atexit(my_exit1) != 0) //注册exit1
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
可见执行顺序与注册顺序相反,且同一个exit handler
注册几次,就调用几次。