Why is using exit() considered bad? [duplicate]

谁说我不能喝 提交于 2019-12-01 04:10:58

Just blindly calling exit() somewhere in your program is considered bad for a simple reason:

It does not properly shutdown other threads (they just get terminated), it does not properly flush all buffers (stdio files are flushed) and guarantee a consistent and valid state of permanent/shared resources (files/shared memory/other ways to communicate).

Still, if you can guarantee that no thread is running which might interfere (by being killed holding a lock or such), and all buffers which need it will be flushed by exit(), that's a valid way to achieve a faster shutdown.

Much modern software is programmed for even faster shutdown:

It is crash-tolerant, in that at nearly every time, just shutting down using e.g. _Exit() (not even calling atexit or at_quick_exit registered hooks) is ok. That is vastly faster than an ordered shutdown in most cases (Windows user interface resources should be destroyed first if possible, because they are an exception).

For further reading: Crash-only software (PDF!)

Crash-only programs crash safely and recover quickly. There is only one way to stop such software - by crashing it - and only one way to bring it up - by initiating recovery. Crash-only systems are built from crash-only components, and the use of transparent component-level retries hides intra-system component crashes from end users. In this paper we advocate a crash-only design for Internet systems, showing that it can lead to more reliable, predictable code and faster, more effective recovery. We present ideas on how to build such crash-only Internet services, taking successful techniques to their logical extreme.

Items 1 and 2, I disagree with. Those are more matters of style and preference.

As to item 3, you should look at the documentation to see what it actually will or will not free or flush (http://en.cppreference.com/w/cpp/utility/program/exit and http://msdn.microsoft.com/en-us/library/6wdz5232.aspx). For instance, the MS documentation says "flushes all file buffers before it terminates the process."

When your program exits, the OS will reclaim the memory, but that's not what he's talking about. What he means is that resources like semaphores won't be released properly or in a timely fashion. Maybe it's a concern, maybe not, depending on what sort of resources you're using.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!