Chinaunix首页 | 论坛 | 博客
  • 博客访问: 225557
  • 博文数量: 27
  • 博客积分: 1151
  • 博客等级: 少尉
  • 技术积分: 426
  • 用 户 组: 普通用户
  • 注册时间: 2010-06-15 19:25
文章分类
文章存档

2012年(5)

2011年(6)

2010年(16)

我的朋友

分类: C/C++

2010-11-28 14:29:30

使你的程序“正常”退出
by firefox@foxmail.com
        ——abort exit 其实差不多

其实很多人所谓的正常退出,基本上指以下两种:
1. 退出前必须完成指定的工作,如向某个远端的端口发消息
2. 退出时要关照到那些打开的流,如要正常将缓冲区的数据输出到文件

这样考虑的话,异常退出就是上面罗列两点反过来...

我们再来关注程序的几种退出方式
1. 自然死亡:main函数的return 0
2. 勇敢自杀:调用 exit 或者 abort
3. 死于非命:被杀手CTRL+C/kill,不小心踩到地雷(触发某些硬件错误),中了流弹(未捕获的信号、异常)

硬件错误、无法捕获的异常这两种情况无法把控,所以这里不详述。其他程序退出方式中,可以被归类为异常退出的,也就不外乎这两类:
1. Ctrl+C kill之类,未完成正常退出时该完成的工作
2. abort exit之类,未完成正常退出时该完成的工作

换句话说,如果被终止时,已经没有需要做的工作,即使是被kill,也可视作正常退出。这里,让我们关注于符合“异常退出”条件的情况。上面列出的两种异常退出的主要区别:
1. 第一类是不会去清理打开的文件描述符的
2. 第二类会清理文件描述符,缓冲区;abort 和 exit 的不同在于是否析构静态和全局对象,exit还可调用atexit注册回调函数,不过如果对SIGABRT信号注册handler,那abort和exit就没什么区别了。

最后,给出简单的结论,不继续展开了。通过下面的方法可正常退出
1. 通过abort或者exit配合回调函数,在退出之前完成需要做的清理工作
2. 捕获常见的"杀手",再执行 1。常见需要捕获的有:SIGINT SIGTERM

-------
信号参考资料:http://www.ibm.com/developerworks/cn/linux/l-ipc/part2/index1.html

abort是会产生core文件的
terminate abort exit 的区别...
  • abort indicates "abnormal" end to the program, and raises the the POSIX signal SIGABRT, which means that any handler that you have registered for that signal will be invoked, although the program will still terminate afterwords in either case. Usually you would use abort in a C program to exit from an unexpected error case where the error is likely to be a bug in the program, rather than something like bad input or a network failure. For example, you might abort if a data structure was found to have a NULL pointer in it when that should logically never happen.

  • exit indicates a "normal" end to the program, although this may still indicate a failure (but not a bug). In other words, you might exit with an error code if the user gave input that could not be parsed, or a file could not be read. An exit code of 0 indicates success. exit also optionally calls handlers before it ends the program. These are registered with the atexit and on_exit functions.

  • std::terminate is what is automatically called in a C++ program when there is an unhandled exception. This is essentially the C++ equivalent to abort, assuming that you are reporting all your exceptional errors by means of throwing exceptions. This calls a handler that is set by the std::set_terminate function, which by default simply calls abort.






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