简体   繁体   English

如何使python守护程序处理systemd信号?

[英]How can I make a python daemon handle systemd signals?

So in essence, I have a python script running as a systemd service. 因此,从本质上讲,我有一个作为systemd服务运行的python脚本。 When I tell it to stop, there is a sleep in there that is longer than the systemd timout, and systemd kills it before the last bit of code runs. 当我告诉它停止时,其中的睡眠时间长于systemd timout,并且systemd在运行最后一行代码之前将其杀死。 The code prior to that is a while loop, and the loop repeats every 15 seconds. 之前的代码是while循环,该循环每15秒重复一次。 How can I make it so the script breaks the loop when systemd sends it a signal? 我如何做到这一点,以便在systemd向其发送信号时脚本打破循环?

Register your handler with signal.signal like this: 使用signal.signal注册您的处理程序,如下所示:

#!/usr/bin/env python
import signal
import sys

isKilled = False

def signal_handler(signal, frame):
    global isKilled
    isKilled = True

signal.signal(signal.SIGINT, signal_handler)
signal.pause()

You can then test for isKilled to see if the program has been sent a kill request. 然后,您可以测试isKilled以查看程序是否已发送isKilled请求。

Note: You may have to change the value of SIGINT to match the command systemd is sending. 注意:您可能必须更改SIGINT的值以匹配systemd正在发送的命令。 It will depend on your use case. 这将取决于您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM