atexit()钩子函数

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);
}

编译执行上述程序,打印结果如下:

image-20230809172525769

从上图可以看到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)  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值