Search code examples
linuxservicesystemdrhel7

How to make systemd monitor background process


Unit file

[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

My script

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

loop()
{
    while true
    do
        sleep 5
    done
}

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

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

Now it works fine when I do systemctl start thiru.service. But when I start the service by directly calling the script /tmp/thiru.sh start, systemctl does not detect that.

[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.

Is there a way to make systemd detect that my service has started? Using PID file maybe?


Solution

  • systemd only monitors processes that it launched itself.

    You don't need to write specific start/stop function in a script anymore. Simply call the main part of your script in ExecStart=.

    You don't need a PID file anymore. systemd can track all the process spawned by your script using cgroups. If systemctl stop thiru does not kill all the processes, then systemctl kill --signal=term thiru will do it.