I have used exit(1) extensively in my code because it does (I hope) exactly what I want - abort the program. I nicely print an error message (or put it into stderr), and then I just leave.
But I heard some schools of thought that this is bad for some reason and I don't understand why. The amount of work one would need to return an error value from every function where it is possible, and then navigate through cascading returns back to main so the program exits "naturally"... Is there a difference?
Are there specific scenarios where it matters? Even when I use errno and perror(), it is still much easier to just exit(1) from the point where the error occurred and without making the code less readable.
Do I have your blessing to use exit(1) ?
CodePudding user response:
It's a choice to make for yourself.
If you're writing a library, you really ought to report failure to the caller, which may be able to recover in ways you can't internally, and which might need to perform other cleanup that's not done by registered atexit() handlers.
If your code might be called from C or other high-level languages, then again, don't unilaterally exit, as that prevents destructors running to perform similar cleanup.
When you check memory use using Valgrind, then exit() will leave lots of objects in the "still accessible" state, making it harder to find your real leaks.
So I generally recommend returning from main(), but would tolerate some use of exit() in program-specific code that's never going to end up in a library.
CodePudding user response:
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.
So, we are know that exit() function causes to kill the current program, but remember to free() any heap allocated resources (if you can) before calling the exit() function.
So, using the exit() is absolutely okay.
