如何让systemd监控后台进程

How to make systemd monitor background process

单元文件

[root@myserver system]# cat /etc/systemd/system/thiru.service
[Unit]
Description=My service

[Service]
Type=forking
PIDFile=/var/run/thiru.pid
ExecStart=/tmp/thiru.sh start
ExecStop=/tmp/thiru.sh stop

我的脚本

[root@myserver system]# cat /tmp/thiru.sh
#!/bin/sh

loop()
{
    while true
    do
        sleep 5
    done
}

if [ "" = "start" ]; then
    loop &
    echo "$!" > /var/run/thiru.pid
fi

if [ "" = "stop" ]; then
    kill $(cat /var/run/thiru.pid)
    rm -f /var/run/thiru.pid
fi

现在我做 systemctl start thiru.service 时它工作正常。但是当我通过直接调用脚本/tmp/thiru.sh start启动服务时,systemctl没有检测到。

[root@myserver system]# /tmp/thiru.sh start
[root@myserver system]# systemctl status thiru.service
thiru.service - My service
   Loaded: loaded (/etc/systemd/system/thiru.service; static)
   Active: inactive (dead)

Jul 27 04:14:08 myserver systemd[1]: Starting My service...
Jul 27 04:14:08 myserver systemd[1]: Started My service.
Jul 27 04:14:17 myserver systemd[1]: Stopping My service...
Jul 27 04:14:17 myserver systemd[1]: Stopped My service.

有没有办法让 systemd 检测到我的服务已经启动?也许使用 PID 文件?

systemd 只监控它自己启动的进程。

您不再需要在脚本中编写特定的 start/stop 函数。只需在 ExecStart=.

中调用脚本的主要部分

您不再需要 PID 文件。 systemd 可以使用 cgroups 跟踪脚本生成的所有进程。如果 systemctl stop thiru 没有杀死所有进程,那么 systemctl kill --signal=term thiru 会杀死所有进程。