Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between exit and kill in C++

Tags:

c++

exit

sigkill

I have written a signal handler to handle a SIG, and I want to kill the process if I get too many of it. So, which of the following code is better, or should I use them both?

  1. exit(-1); // or some other exit code
  2. kill(getpid(), SIGKILL);
like image 473
maidamai Avatar asked Jan 20 '26 15:01

maidamai


2 Answers

You probably don't want either one, but what you do want is much closer to exit than to kill.

kill is something else coming in from the outside, and forcibly destroying a process. exit is the process itself deciding to quit executing. The latter is generally preferable.

As to why exit isn't the right answer either: most C++ code depends on destructors to clean up objects as you exit from a scope. If you call exit, that won't generally happen--you call exit, it exits to the OS, and no destructors get called in between (except things registered with onexit).

Instead, you generally want to throw an exception that's typically only caught in main, and exits gracefully when it is caught:

int main() { 
    try {
        do_stuff();
    }
    catch(time_to_die const &) {
    }
}

The advantage in this case is that when you do a throw time_to_die;, it automatically unwinds the stack, executing the destructors for all local objects as it goes. When it gets back to main, you get a normal exit, with all destructors having executed, so (assuming proper use of RAII) all your files, network connections, database connections, etc., have been closed as expected, any caches flushed, and so on, so you get a nice, graceful exit.

Short summary: as a rule of thumb, C++ code should never call exit. If your code is completely stuck in a crack, and you want to exit immediately, you want to call abort. If you want a semi-normal exit, do it by throwing an exception that will get you back to main so you can clean things and up and exit gracefully.

like image 121
Jerry Coffin Avatar answered Jan 23 '26 04:01

Jerry Coffin


Difference between exit and kill in C++

One difference is that kill function is not specified in the C++ standard library. It is merely specified in POSIX. exit is standard C++.

Another difference is that kill(getpid(), SIGKILL) will cause the operating system terminates the process forcefully. exit instead performs cleanup (by calling a atexit callback, and flushing streams etc.) and terminates the execution voluntarily.

So, which of the following code is better, or should I use them both?

Depends on the use case, but usually exit is more sensible, since one usually wants the cleanup that it provides.

like image 30
eerorika Avatar answered Jan 23 '26 04:01

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!