zoukankan      html  css  js  c++  java
  • atexit函数基本应用

    很多时候我们需要在程序退出的时候做一些诸如释放资源的操作,但程序退出的方式有很多种,比如main()函数运行结束、在程序的某个地方用exit() 结束程序、用户通过Ctrl+C或Ctrl+break操作来终止程序等等,因此需要有一种与程序退出方式无关的方法来进行程序退出时的必要处理。方法就 是用atexit()函数来注册程序正常终止时要被调用的函数。

        atexit()函数的参数是一个函数指针,函数指针指向一个没有参数也没有返回值的函数。atexit()的函数原型是:int atexit (void (*)(void));

        在一个程序中最多可以用atexit()注册32个处理函数,这些处理函数的调用顺序与其注册的顺序相反,也即最先注册的最后调用,最后注册的最先调用(这个就好比堆栈,先进后出)。

    示例代码:

    /*
    * =====================================================================================
    *
    * Filename: atexit.c
    *
    * Description: atexit test
    *
    * Version: 1.0
    * Created: 2011-4-25 8:29:03
    * Revision: none
    * Compiler: gcc
    *
    * Author: wen hao (WH), hnrain1004@gmail.com
    * Company: other
    *
    * =====================================================================================
    */
    #include
    <stdio.h>
    #include
    <stdlib.h>
    #include
    <unistd.h>
    #include
    <stdlib.h>

    void func(void);
    /*
    * === FUNCTION ======================================================================
    * Name: main
    * Description:
    * =====================================================================================
    */
    int
    main (
    int argc, char *argv[] )
    {
    atexit(func);
    printf(
    "this is the main function\n");
    sleep(
    1);
    return EXIT_SUCCESS;
    }
    /* ---------- end of function main ---------- */

    void func(void)
    {
    printf(
    "this is the func function\n");
    sleep(
    1);
    }

    运行结果:

    [root@localhost test]# ./atexit

    this is the main function

    this is the func function

  • 相关阅读:
    python3+request接口自动化框架
    类型转换函数
    操作符重载(三)
    操作符重载(二)
    操作符重载(一)
    时间获取函数
    文件和目录
    Linux五种IO模型
    类中的函数重载
    系统调用IO和标准IO
  • 原文地址:https://www.cnblogs.com/hnrainll/p/2026651.html
Copyright © 2011-2022 走看看