Gin*_*ger 4 python linux systemd
我有一个作为服务运行的Python脚本.它写入磁盘.如果用户在服务上调用systemctl stop,我想以自己的方式处理该命令以降低文件损坏的风险.
如何捕获systemctl stop命令?
我在/ usr/lib/systemd/system中的文件是:
[Unit]
Description=foo
[Service]
Type=simple
ExecStart=/usr/bin/python /srv/go.py
User=jon
Restart=always
[Install]
WantedBy=graphical.target
Run Code Online (Sandbox Code Playgroud)
我的Python脚本是:
#!/usr/bin/python
import time
import datetime
import threading
def worker():
while True:
with open('/tmp/go.txt', 'a') as f:
s = str(datetime.datetime.utcnow()) + '\n'
f.write(s)
print(s)
time.sleep(1)
if __name__=='__main__':
t = threading.Thread(target=worker)
t.start()
Run Code Online (Sandbox Code Playgroud)
如systemd文档中所述,进程将SIGTERM立即接收,然后立即进行SIGHUP.过了一段时间,SIGKILL会发送.
所有信号以及发送它们的策略都可以在相关的服务文件中进行更改.
请参阅另一个stackoverflow问题,了解如何在Python程序中处理这些信号.