105

I am using a systemd service which calls a process when it's been "started" (e.g. systemctl start test.service). As per the design, the process stays in a loop forever, we are able to see process existence using the ps command. We have also seen that the process is getting killed (as intended) for systemctl stop command. However, our requirement is that we want to do some safe shutdown operations from within the process before it gets killed. But I am not sure how to detect a systemd stop operation from within the process.

Does a systemctl stop test.service command send SIGKILL or SIGTERM signal to kill the process? How can I detect a systemctl stop operation from within a process?

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
user3805417
  • 1,051
  • 2
  • 7
  • 4

2 Answers2

148

By default, a SIGTERM is sent, followed by 90 seconds of waiting followed by a SIGKILL.

Killing processes with systemd is very customizable and well-documented.

I recommend reading all of man systemd.kill as well as reading about ExecStop= in man systemd.service.

To respond to those signals, refer to the signal handling documentation for the language you are using.

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
Mark Stosberg
  • 12,961
  • 6
  • 44
  • 49
  • 5
    Worth noting: If the main process stops before reaching the timeout, systemd will send SIGKILL to all child processes, if there are any left. If the timeout is reached, it will send SIGKILL to the entire control group. – Steen Schütt Dec 01 '20 at 13:26
  • You can use `KillMode` https://www.freedesktop.org/software/systemd/man/systemd.kill.html#KillMode= to adjust what happens to the children of main process. The default behavior is to kill any remaining children when main process ends (because typically this is needed to free all leaked resources, because well-behaving main process will not end before `wait()`:n for all children to stop). – Mikko Rantalainen Mar 27 '23 at 13:16
4

Does a systemctl stop test.service command send SIGKILL or SIGTERM signal to kill the process? How can i detect a systemctl stop operation from within a process?

Systemd sends SIGTERM signal to process. In process you have to register signals, which are "caught".

In process, eg. SIGTERM signal can be registered like this:

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

When SIGTERM is sent to the process, the signal_callback() function is executed.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
  • 1
    Note that this is pseudocode for what happens. It is dangerous to do any file IO (like printf) in a signal handler in general. If all you care about is printing the message and then possible crashing afterwards, that's fine. But if you want to handle the signal correctly, the signal handler should just set a thread safe variable (say std::atomic) and your main event loop should watch that thread safe variable. – Mark Lakata May 17 '23 at 16:09