在 Raspbian Jessie 上,我正在编写一个由 systemd 自动运行的 Python 脚本。作为 SSCCE,让我们编写一个简单的 Python 脚本作为服务:
cat >/home/pi/service.py <<EOF
from time import sleep
sleep(99999)
EOF
这是可以通过 SIGINT 中断的,因此我像这样设置服务并告诉 systemd SIGINT 是关闭它的正确方法:
cat >/lib/systemd/system/python-service.service <<EOF
[Unit]
Description=Python service
[Service]
Type=simple
TTYPath=/dev/tty1
StandardInput=tty
StandardOutput=tty
ExecStart=/usr/bin/nohup /usr/bin/python /home/pi/service.py
KillSignal=SIGINT
SuccessExitStatus=SIGINT
[Install]
WantedBy=multi-user.target
EOF
然后我设置 systemd 来启动该服务:
systemctl set-default multi-user.target
systemctl daemon-reload
systemctl enable python-service.service
该服务已正确设置、运行并可以停止,但除非重新启动,否则无法重新启动:
# I first check that the service has been run at startup:
pi@raspberrypi:~ $ systemctl status python-service.service
● python-service.service - Python service
Loaded: loaded (/lib/systemd/system/python-service.service; enabled)
Active: active (running) since Mon 2017-01-09 01:56:47 UTC; 59s ago
Main PID: 419 (python)
CGroup: /system.slice/python-service.service
└─419 /usr/bin/python /home/pi/service.py
# It runs fine, now I stop it
pi@raspberrypi:~ $ sudo systemctl stop python-service.service
# Let's start it again
pi@raspberrypi:~ $ sudo systemctl start python-service.service
# And consult the current status, I assume the parenthesis mean there is an issue
pi@raspberrypi:~ $ systemctl status python-service.service
● python-service.service - Python service
Loaded: loaded (/lib/systemd/system/python-service.service; enabled)
Active: active (running) since Mon 2017-01-09 01:59:54 UTC; 2s ago
Main PID: 833 ((nohup))
CGroup: /system.slice/python-service.service
└─833 (nohup)
# And indeed no service.py is running
pi@raspberrypi:~ $ ps ax|grep service
839 pts/0 S+ 0:00 grep --color=auto service