----参照网络视频整理
也可以使用on_exit,大同小异,一般习惯用atexit().
以atexit() 注册的函数,会以注册的逆序(reverse order)释放。
atexit ----register a function to be called at normal process termination
进程正常终止时,函数会被调用,用来注册钩子函数。
解释:进程正常终止时,会调用钩子函数,释放该释放的内容。
钩子函数,类似C++中的析构函数。
#include <stdio.h>
#include <stdlib.h>
static void f1(void)
{
puts("f1() is working");
}
static void f2(void)
{
puts("f2() is working");
}
static void f3(void)
{
puts("f3() is working");
}
int main()
{
puts("Begin");
//以下三个atexit不是函数调用,而是当调用exit的时候才会调用,并且是按照注册的逆序调用
atexit(f1);
atexit(f2);
atexit(f3);
puts("End");
exit(0);
}
钩子函数的用途:当程序调用exit()时,会自动调用钩子函数,对资源进行释放、清理。
//无钩子函数,当需要打开多个fd时,都需要对前面的fd进行close();
fd1 = open()
if(fd1<0)
{
perror();
exit();
}
fd2 = open()
if(fd2<0)
{
close(fd1);//
perror();
exit();
}
........
fd100 = open()
if(fd100<0)
{
close(fd1);//
....
close(fd99);//
perror();
exit();
}
修改:
//每次都写一个钩子函数,带exit时,自动调用钩子函数。
fd1 = open()
if(fd1<0)
{
perror();
exit(1);
}
atexit(); ----------->close(fd1);
fd2 = open()
if(fd2<0)
{
// close(fd1);//省了该语句。
perror();
exit(1);//-------------执行这句时会调用钩子函数
}
atexit(); ----------->close(fd2);
........
fd100 = open()
if(fd100<0)
{
//close(fd1);//
//....
// close(fd99);//
perror();
exit(1);//-------------执行这句时会调用钩子函数
}
总结:
1、进程进程退出时使用exit
2、为了避免内存泄露,使用钩子函数。