atexit()钩子函数
用于注册在程序退出时自动执行的函数。被注册的函数类型为 void function(void)
,当程序正常退出前逆序调用已注册的函数,并且每个函数只会被调用一次。
函数原型如下:
#include <stdlib.h>
int atexit(void (*function)(void));
参数说明:
function:指向要在程序退出时自动调用的函数的指针。
如果成功注册了函数,它会返回 0;如果注册失败,它会返回非零值。
使用atexit()的示例
代码示例:
test.c
static void fun1(void)
{
puts("fun1() is workong!");
}
static void fun2(void)
{
puts("fun2() is workong!");
}
static void fun3(void)
{
puts("fun3() is workong!");
}
int main()
{
puts("Begin!");
//将fun1、fun2、fun3注册为退出执行函数
atexit(fun1);
atexit(fun2);
atexit(fun3);
puts("End!");
exit(0);
}
编译执行上述程序,打印结果如下:
从上图可以看到atexit()
注册的函数,在程序退出前,被逆序的调用。
atexit()函数的作用
看下面的伪码,如果open100个文件,那么需要close的函数数量是1+2+…99个
fd1 = open();
if(fd1 < 0)
{
perror();
exit(1);
}
fd2 = open();
if(fd2 < 0)
{
close(fd1);
perror();
exit(1);
}
......
fd99 = open();
if(fd100 < 0)
{
close(fd1);
close(fd2);
...
close(fd98);
perror();
exit(1);
}
fd100 = open();
if(fd100 < 0)
{
close(fd1);
close(fd2);
...
close(fd99);
perror();
exit(1);
}
这时候如果使用atexit()代码就可以改为下面这种,close函数需要调用100次就可以了。
fd1 = open();
if(fd1 < 0)
{
perror();
exit(1);
}
//钩子函数注册close函数关闭fd1,当fd2...fd100打开失败,都会执行exit(),在执行前会执行close(fd1)
atexit();--->close(fd1)
fd2 = open();
if(fd2 < 0)
{
perror();
exit(1);
}
//钩子函数注册close函数用来关闭fd2,当fd3...fd100打开失败,都会执行exit(),在执行前会执行close(fd2)
atexit();--->close(fd1)
......
fd99 = open();
if(fd99 < 0)
{
close(fd1);
close(fd2);
...
close(fd98);
perror();
exit(1);
}
//钩子函数注册close函数用来关闭fd99,当fd100打开失败,会执行exit(),在执行前会执行close(fd99)
atexit();--->close(fd99)
fd100 = open();
if(fd100 < 0)
{
/*这里面的代码就不用写了
close(fd1);
close(fd2);
...
close(fd99);
*/
perror();
exit(1);
}
//钩子函数注册close函数用来关闭fd100,当程序正常退出会执行close(fd99)
atexit();--->close(fd100)