0

I have basically a console C++ app for Linux CentOS9. I am going to run it as a service using systemctl start/stop.

Currently the app exits if user press Enter in the console but this wont be possible in service mode as the user wont see the app console after logging in.

What can be done so I the app can detect it is being stopped/terminated so it can cleanup resources (closing files)?

Boppity Bop
  • 9,613
  • 13
  • 72
  • 151
  • 1
    Send it a [`SIGTERM`](https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html)? – Paul Sanders Apr 09 '22 at 14:50
  • how do I "intercept" it in the code? I need to run cleanup upon it – Boppity Bop Apr 09 '22 at 15:34
  • 3
    Take a look at [this](https://www.gnu.org/software/libc/manual/html_node/Basic-Signal-Handling.html). But be aware that the POSIX (and hence runtime library) functions that you can safely call in a signal hander is a very limited subset, see [here](https://man7.org/linux/man-pages/man7/signal-safety.7.html). The usual procedure is to set a flag in the signal handler that is inspected by the mainline code periodically and it then shuts down gracefully. Declare the flag as `volatile` to guarantee that changes made to it in the signal handler are seen in the mainline code. – Paul Sanders Apr 09 '22 at 15:53
  • 2
    There is also some information about which system calls terminate early when a signal is received and under what circumstances [here](https://man7.org/linux/man-pages/man7/signal.7.html), which you might find useful. – Paul Sanders Apr 09 '22 at 15:54
  • so if I write `sigwait` in the end of `main` it will suspend main thread but not the others right? (this is what I need but am confused by "suspend execution" - i dont want all threads to be suspended).. in any rate - if you could write few lines sample as an answer ill accept it. thank you – Boppity Bop Apr 09 '22 at 16:05
  • 2
    From the [documentation](https://man7.org/linux/man-pages/man3/sigwait.3.html) (emphasis mine): "The sigwait() function suspends execution **of the calling thread** until one of the signals specified in the signal set set becomes pending." – Paul Sanders Apr 09 '22 at 17:09

1 Answers1

0

It seems systemctl stop sends SIGTERM.

Just register callback for it

void signal_callback()
{
    printf("Process is going down\n");
}
signal(SIGTERM, signal_callback)

How systemd stop command actually works

Boppity Bop
  • 9,613
  • 13
  • 72
  • 151