I am new to C programming. I used to think using exit()
was the cleanest way of process termination (as it is capable of removing temporary files, closing open files, normal process termination...), but when I tried man exit
command on the terminal (Ubuntu 16.04.5, gcc 5.4.0) I saw the following line:
The exit() function uses a global variable that is not protected, so it is not thread-safe.
After that I tried to make some research about better replacement for exit()
(to change my programming behavior from the beginning). While doing that I faced with this question in which side effects of exit()
is mentioned and it is suggested to use atexit()
properly to solve the problem (at least partially).
There were some cases in which using abort()
was preferred over exit()
. On top of that, this question suggests that atexit()
might also be harmful.
So here are my questions:
exit()
and is not harmful for the system at any case)?exit() vs _Exit() function in C and C++ So what is the feature of this function? The exit() function performs some cleaning before terminating the program. It clears the connection termination, buffer flushes etc. This _Exit() function does not clean anything.
Yes, it is ok to use exit in C.
Passing EXIT_FAILURE causes the program to terminate with a status indicating failure. The meanings of other argument values are not specified by the C language. You'll commonly see exit(1) to denote failure, but that's not entirely portable.
C library function - exit()The C library function void exit(int status) terminates the calling process immediately. Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.
what is the best possible way of process terminating
exit()
, as your code is not going multi-threaded.exit()
because of 1. above.Given that power/hardware fails can happen at any time, the imposs.. extreme difficulty of reliably terminating threads with user code and the chaotic nature of the use of memory pools etc. in many non-trivial multithreaded apps, it is better to design apps and systems that can clean temp files etc. on start-up, rather than trying to micro-manage shutdown.
'Clean up all the resources you allocate before you exit' sounds like good advice in a classroom or lecture, but quickly becomes a whole chain of albatross round your neck when faced with a dozen threads, queues and pools in a continually changing dynamic system.
If you can, if you are running under a non trivial OS, let it do its job and clean up for you. It's much better at it than your user code will ever be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With