是否可以更改使用atexit()注册的函数中的退出代码?

前端之家收集整理的这篇文章主要介绍了是否可以更改使用atexit()注册的函数中的退出代码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
atexit(3)的手册页说明如下:

POSIX.1-2001 says that the result of calling exit(3) more than once (i.e.,calling exit(3) within a function registered using atexit()) is undefined. On some systems (but not Linux),this can result in an infinite recursion; portable programs should not invoke exit(3) inside a function registered using atexit().

但是,我有兴趣在我的程序的终结器中修改退出代码.我设法做到这一点的唯一方法是从我的终结函数调用exit(),但是手册页明确地警告了这一点.

这样做有什么实际危险吗?是否有任何实现方法可能会导致问题?更好的是,还有另一种方法吗?

解决方法

你可以拨打 _exit().

在手册页的Notes部分中:

The function _exit() is like exit(),but does not call any functions registered with atexit() or on_exit().

这应该避免POSIX规范中警告的“递归”问题.如果你能以某种方式保证你的“退出代码更改”退出处理程序最后运行,这应该完美地工作,模拟Notes中列出的警告:

Whether it flushes standard I/O buffers and removes temporary files created with tmpfile(3) is implementation-dependent. On the other hand,_exit() does close open file descriptors,and this may cause an unknown delay,waiting for pending output to finish. If the delay is undesired,it may be useful to call functions like tcflush(3) before calling _exit(). Whether any pending I/O is canceled,and which pending I/O may be canceled upon _exit(),is implementation-dependent.

原文链接:https://www.f2er.com/c/118320.html

猜你在找的C&C++相关文章