用atexit()处理C/C++程序的退出

    很多时候我们需要在程序退出的时候做一些诸如释放资源的操作,但程序退出的方式有很多种,比如main()函数运行结束、在程序的某个地方用exit()结束程序、用户通过Ctrl+C或Ctrl+break操作来终止程序等等,因此需要有一种与程序退出方式无关的方法来进行程序退出时的必要处理。方法就是用atexit()函数来注册程序正常终止时要被调用的函数。

    atexit()函数的参数是一个函数指针,函数指针指向一个没有参数也没有返回值的函数。atexit()的函数原型是:int atexit (void (*)(void));

    在一个程序中最多可以用atexit()注册32个处理函数,这些处理函数的调用顺序与其注册的顺序相反,也即最先注册的最后调用,最后注册的最先调用。

下面是一段代码示例:
程序的运行结果为:

  1. #include <stdlib.h> // 使用atexit()函数所必须包含的头文件stdlib.h
  2. #include <iostream.h>
  3. void terminate() 
  4. {
  5.     cout<<"program is terminating now..."<<endl;
  6. }
  7. int main(void)
  8. {
  9.     // 注册退出处理函数
  10.     atexit(terminate);
  11.     cout<<"the end of main()"<<endl;
  12.     return 0;
  13. }

程序的运行结果为:
the end of main()
program is terminating now...

原文:http://blog.youkuaiyun.com/abcwangdragon/archive/2006/10/24/1349203.aspx

 

 

msdn上的例子:

  1. // crt_atexit.c
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. void fn1( void ), fn2( void ), fn3( void ), fn4( void );
  5. int main( void )
  6. {
  7.    atexit( fn1 );
  8.    atexit( fn2 );
  9.    atexit( fn3 );
  10.    atexit( fn4 );
  11.    printf( "This is executed first./n" );
  12. }
  13. void fn1()
  14. {
  15.    printf( "next./n" );
  16. }
  17. void fn2()
  18. {
  19.    printf( "executed " );
  20. }
  21. void fn3()
  22. {
  23.    printf( "is " );
  24. }
  25. void fn4()
  26. {
  27.    printf( "This " );
  28. }
Output
This is executed first.
This is executed next.
出自:http://msdn.microsoft.com/zh-cn/asp.net/tze57ck3(VS.80).aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值