Python在关机命令下未接收到SIGTERM信号
我已经用Python在树莓派上编程几个月了,现在我想让我的脚本在收到SIGTERM信号时能够“乖乖地”关闭(比如关闭文件,确保不再往SD卡写入数据)。
根据StackOverflow上的建议(1, 2),我可以在手动杀掉进程时处理SIGTERM信号(也就是用kill {进程编号}),但是如果我发送关机命令(比如shutdown -t 30 now),我的处理程序就不会被调用。
我还尝试注册所有信号,并在关机事件时检查发送的信号,但我没有收到任何信号。
这里有个简单的示例代码:
import time
import signal
import sys
def myHandler(signum, frame):
print "Signal #, ", signum
sys.exit()
for i in [x for x in dir(signal) if x.startswith("SIG")]:
try:
signum = getattr(signal, i)
signal.signal(signum, myHandler)
print "Handler added for {}".format(i)
except RuntimeError,m:
print "Skipping %s"%i
except ValueError:
break
while True:
print "goo"
time.sleep(1)
任何建议都非常感谢.. =)
1 个回答
0
这段代码在我的树莓派上运行得很好,重启后我能在文件output.log中看到正确的输出:
logging.basicConfig(level=WARNING,
filename='output.log',
format='%(message)s')
def quit():
#cleaning code here
logging.warning('exit')
sys.exit(0)
def handler(signum=None, frame=None):
quit()
for sig in [signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT, signal.SIGKILL]:
signal.signal(sig, handler)
def restart():
command = '/sbin/shutdown -r now'
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
logging.warning('%s'%output)
restart()
可能是你的终端在Python脚本之前就处理了信号,所以你实际上看不到任何东西。试着把输出写到一个文件里(可以用日志模块或者你喜欢的其他方式)。