Chinaunix首页 | 论坛 | 博客
  • 博客访问: 399618
  • 博文数量: 83
  • 博客积分: 2011
  • 博客等级: 大尉
  • 技术积分: 741
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-04 22:51
文章分类

全部博文(83)

文章存档

2009年(83)

我的朋友

分类: LINUX

2009-10-06 13:14:54

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.

 
阅读(2009) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~