启动我的守护进程时Systemctl阻塞

时间:2019-02-13 13:51:49

标签: python linux daemon systemd

我用以下代码在Python中编写了一个小守护程序:

#!/usr/bin/python3

import time
import click
import daemonocle

from daemonocle.cli import DaemonCLI

@click.command(cls=DaemonCLI, daemon_params={'pidfile': '/var/run/daemon.pid'})
def main():
    while True:
        time.sleep(3)

if __name__ == '__main__':
    main()

它按原样工作很好。如果执行以下操作,我将获得良好的退出状态0

$ sudo ./daemon start 
Starting daemon ... OK    

$ echo $?
0

然后我写了一个systemd服务文件:

[Unit]
SourcePath=/home/pi/daemon/daemon
Description=My First Daemon
Before=multi-user.target
After=mosquitto.target

[Service]
Type=forking
PIDFile=/var/run/daemon.pid
Restart=no
ExecStart=/home/pi/daemon/daemon start
ExecStop=/home/pi/daemon/daemon stop
ExecReload=/home/pi/daemon/daemon reload

如果我尝试使用systemctl运行守护程序,该命令仍然处于阻塞状态:

$ sudo systemctl start daemon
^C
$ sudo systemctl status daemon
? daemon.service - XEMWAY Demo Service
   Loaded: loaded (/home/pi/daemon/daemon; static; vendor preset: enabled)
   Active: activating (start) since Wed 2019-02-13 13:47:40 GMT; 12s ago
  Process: 13044 ExecStop=/home/pi/daemon/daemon stop (code=exited, status=0/SUCCESS)
 Main PID: 12304 (code=exited, status=143); Control PID: 13079 (daemon)
   CGroup: /system.slice/daemon.service
           +-13079 /usr/bin/python3 /home/pi/daemon/daemon start
           +-13081 /usr/bin/python3 /home/pi/daemon/daemon start

systemd一分钟后说:

2月13日13:49:10 raspberrypi systemd [1]:daemon.service:设备进入失败状态。 2月13日13:49:10 raspberrypi systemd [1]:daemon.service:失败,结果为“超时”。

这怎么了?

1 个答案:

答案 0 :(得分:1)

问题是您的服务自己创建了守护进程,而systemd却不知道。这只是一个简单的程序,在为systemd花费很少的时间后即可运行并退出。您要使用forking而不是simple

Type=simple

Systemd仍会以守护进程的身份跟踪您的进程,因为它知道其pid:

系统控制状态为test2.service

* test2.service - My First Daemon
   Loaded: loaded (/tmp/a.py; static; vendor preset: disabled)
   Active: active (running) since Wed 2019-02-13 16:06:27 EET; 5s ago
 Main PID: 18104 (python)
    Tasks: 2 (limit: 4915)
   Memory: 10.1M
   CGroup: /system.slice/test2.service
           |-18104 /usr/bin/python /tmp/a.py start
           `-18115 /usr/bin/python /tmp/a.py start