2

We know that in the world of Linux-Unix, we can break the program running in the foreground in the terminal with ctrl+C and end the program.

How can I know in C++ that a third party breaks or forces kill (kill -9) the program?

Do I have to check something with the thread constantly? I have to return exit status 130 in my program when the program is broken and 140 exit status when the program is killed.

genpfault
  • 51,148
  • 11
  • 85
  • 139
  • 1
    Are you looking for something like this: https://stackoverflow.com/questions/4217037/catch-ctrl-c-in-c – Jabberwocky Apr 19 '23 at 08:37
  • That's right, it can be done with a signal But how do I know that the program is force-killed? –  Apr 19 '23 at 08:44
  • Most signals you can catch, some you can't. And there's no way to distinguish from where the signal originates. It will all come from the `kill` system-call. – Some programmer dude Apr 19 '23 at 08:52
  • Actually it seems you cannot catch `SIGKILL` (unlike like `SIGINT`). Read this: https://unix.stackexchange.com/questions/485644/what-does-a-program-do-when-its-sent-sigkill-signal and this: https://stackoverflow.com/questions/3908694/sigkill-signal-handler – Jabberwocky Apr 19 '23 at 08:52
  • 2
    You cannot catch or handle SIGKILL. Your program is terminated instantly. – Jesper Juhl Apr 19 '23 at 08:53
  • What about the `kill`? Can I catch or handle a `kill`? (not `kill -9`) I had heard that in the simple `kill` command, the operating system somehow asks the program to kill it, and the program is killed after doing the necessary work. –  Apr 19 '23 at 09:09
  • 3
    What is your actual assignment? What are your requirements? What are your limitations? What is the original and underlying problems you need to solve? – Some programmer dude Apr 19 '23 at 09:27
  • What I want is for when my program is killed and then the user enters the `$?` command, sees the `130` output @Someprogrammerdude –  Apr 20 '23 at 05:27

1 Answers1

5

Some signals sent via kill() can be caught and handled. Some cannot (like SIGKILL which is what kill -9 results in). Your program is simply terminated and cleaned up by the kernel - it doesn't get any chance to notice what happened or react to it in any way. From your programs point of view it is equivalent to the user pulling the power from the computer - the program just dies as if shot in the head.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70