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