且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我们应该在C ++中使用exit吗?

更新时间:2023-11-10 11:21:46

问题是,不是你可能以某种方式取得所有权的一切都被列入标准清理。 p>

例如,许多程序和库都会执行创建锁定文件,启动后台进程,更改系统设置等操作。如果调用 exit ,这些可能会被操作系统清除,但不一定要。未能释放这些可能会产生从无法重新启动程序(典型的锁文件)到整个系统故障(不太可能,但在某些情况下可能)。



真的,主题轶事。我以前使用 OIS ,一个输入库,为我的项目。每次我在调试器中杀死我的程序,密钥重复被系统范围内打破,因为OIS在Linux中暂时禁用它。我通过更改设置(和以后倾销OIS完全)修复它,但这说明很好的问题,你可能会遇到调用 exit 之前你自己清理环境。


According to C++ reference

exit terminates the process normally, performing the regular cleanup for terminating programs.

Normal program termination performs the following (in the same order): Objects associated with the current thread with thread storage duration are destroyed (C++11 only). Objects with static storage duration are destroyed (C++) and functions registered with atexit are called. All C streams (open with functions in ) are closed (and flushed, if buffered), and all files created with tmpfile are removed. Control is returned to the host environment.

Note that objects with automatic storage are not destroyed by calling exit (C++).

as far as i know, when the process terminated, all the storage used by the process are reclaimed, so what's the impact that objects with automatic storage are not destroyed?

The problem is the fact not everything you might somehow take ownership of is listed in the standard as getting cleaned up.

For example, many programs and libraries do things like create lock files, start background processes, change system settings, and so on. These may be cleaned up by the OS if you call exit, but they aren't required to be. Failing to release these could have effects ranging from being unable to restart the program (typical of lock files) to total system failure (less likely, but possible in some cases).

True, on-topic anecdote. I used to use OIS, an input library, for my project. Every time I killed my program in the debugger, key repeat was broken system-wide, because OIS 'temporarily' disabled it in Linux. I fixed it by changing settings (and later dumping OIS entirely), but this illustrates very well the sort of issues you might run into calling exit before you have cleaned up your environment yourself.