In C and C++, what is the difference between exit()
and abort()
? I am trying to end my program after an error (not an exception).
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to get the return code of a shell script in lu
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
The following things happen when a program calls
exit
():atexit
function are executedtmpfile
are removedThe
abort
() function sends theSIGABRT
signal to the current process, if it is not caught the program is terminated with no guarantee that open streams are flushed/closed or that temporary files created viatmpfile
are removed,atexit
registered functions are not called, and a non-zero exit status is returned to the host.abort
sends theSIGABRT
signal.abort
does not return to the caller. The default handler for theSIGABRT
signal closes the application.stdio
file streams are flushed, then closed. Destructors for C++ class instances are not, however (not sure on this one -- perhaps results are undefined?).exit
has its own callbacks, set withatexit
. If callbacks are specified (or only one), they are called in the order reverse of their registration order (like a stack), then the program exits. As withabort
,exit
does not return to the caller.stdio
file streams are flushed, then closed. Also, destructors for C++ class instances are called.abort()
exits your program without calling functions registered usingatexit()
first, and without calling objects' destructors first.exit()
does both before exiting your program. It does not call destructors for automatic objects though. SoWill destruct
a
andb
properly, but will not call destructors ofc
.abort()
wouldn't call destructors of neither objects. As this is unfortunate, the C++ Standard describes an alternative mechanism which ensures properly termination:Instead of calling
exit()
, arrange that codethrow exit_exception(exit_code);
instead.From the exit() manual page:
From the abort() manual page:
abort sends a SIGABRT signal, exit just closes the application performing normal cleanup.
You can handle an abort signal however you want, but the default behavior is to close the application as well with an error code.
abort will not perform object destruction of your static and global members, but exit will.
Of course though when the application is completely closed the operating system will free up any unfreed memory and other resources.
In both abort and exit program termination (assuming you didn't override the default behavior), the return code will be returned to the parent process that started your application.
See the following example:
Comments:
If abort is uncommented: nothing is printed and the destructor of someobject will not be called.
If abort is commented like above: someobject destructor will be called you will get the following output: