使用atexit()函数来注册钩子函数

239 篇文章 11 订阅

----参照网络视频整理 

也可以使用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、为了避免内存泄露,使用钩子函数。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值