Chinaunix

标题: atexit函数 [打印本页]

作者: tancotq    时间: 2009-10-06 13:14
标题: atexit函数
1、函数原型int atexit( void (__cdecl *func )( void ));
2、功能:注册程序正常终止时要被调用的函数#include  
#include  
void exit_fn1(void)
{
   printf("Exit function #1 called\n");
}
void exit_fn2(int a)
{
   printf("Exit function #2 called, a = %d\n",a);
}
int main(void)
{
   /* post exit function #1 */
   atexit(exit_fn1);
   /* post exit function #2 */
   atexit(exit_fn2(2));
   return 0;
}
程序编译不过,原因:atexit的参数是指向函数的指针,一个函数名(不带参数)就可以表示指向该函数的指针,所以正确。而函数名带上参数就是调用函数,然后以函数返回值作为atexit的参数,而你程序中的函数返回值不是指向函数的指针,所以出错。注:atexit 里面的函数是不能带参数的The atexit function is passed the address of a function (func) to be called when the program terminates normally. Successive calls to atexit create a register of functions that are executed in last-in, first-out (LIFO) order. The functions passed to atexit cannot take parameters. atexit and _onexit use the heap to hold the register of functions. Thus, the number of functions that can be registered is limited only by heap memory
3、相关例子// crt_atexit.c
#include
#include
void fn1( void ), fn2( void ), fn3( void ), fn4( void );
int main( void )
{
   atexit( fn1 );
   atexit( fn2 );
   atexit( fn3 );
   atexit( fn4 );
   printf( "This is executed first.\n" );
}
void fn1()
{
   printf( "next.\n" );
}
void fn2()
{
   printf( "executed " );
}
void fn3()
{
   printf( "is " );
}
void fn4()
{
   printf( "This " );
}Output This is executed first.
This is executed next.This program pushes four functions onto the stack of functions to be executed when atexit is called.
When the program exits, these programs are executed on a last in, first out basis.


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/94311/showart_2064785.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2