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

posted @ 2011-04-25 08:38  hnrainll  阅读(469)  评论(1编辑  收藏  举报