107

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?

2 Answers 2

150

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.

2
  • 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. Dec 1, 2020 at 13:26
  • You can use KillMode freedesktop.org/software/systemd/man/… 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). Mar 27, 2023 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.

1
  • 2
    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<bool>) and your main event loop should watch that thread safe variable. May 17, 2023 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.