atexit(3)
的手册页说明如下:
POSIX.1-2001 says that the result of calling
exit(3)
more than once (i.e.,callingexit(3)
within a function registered usingatexit()
) is undefined. On some systems (but not Linux),this can result in an infinite recursion; portable programs should not invokeexit(3)
inside a function registered usingatexit()
.
但是,我有兴趣在我的程序的终结器中修改退出代码.我设法做到这一点的唯一方法是从我的终结函数中调用exit(),但是手册页明确地警告了这一点.
解决方法
_exit()
.
在手册页的Notes部分中:
The function
_exit()
is likeexit()
,but does not call any functions registered withatexit()
oron_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 liketcflush(3)
before calling_exit()
. Whether any pending I/O is canceled,and which pending I/O may be canceled upon_exit()
,is implementation-dependent.