免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1110 | 回复: 0
打印 上一主题 下一主题

atexit函数 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-10-06 13:14 |只看该作者 |倒序浏览
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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP