Systemd stop 命令实际上是如何工作的

我正在使用一个 Systemd 服务,它在进程“启动”时调用进程(例如 systemctl start test.service)。根据设计,进程永远停留在一个循环中,我们能够使用‘ ps’命令看到进程的存在。我们还看到对于 systemctl stop命令,进程正在被终止(正如预期的那样)。 然而,我们的需求是,我们希望在流程被终止之前,从流程内部执行一些安全的关闭操作。但是我不确定如何从进程中检测系统停止操作。

systemctl stop test.service命令是发送 SIGKILL还是 SIGTERM信号来终止进程?如何检测进程内的 systemctl stop操作?

69106 次浏览

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.

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 "catched".

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 process signal_callback() function is executed.