繁体   English   中英

关机命令后python未收到SIGTERM信号

[英]SIGTERM signal not received by python on shutdown command

我已经为raspberryPi使用python编程了几个月了,我正在尝试使我的脚本“表现良好”,并在收到SIGTERM时包装好(关闭文件并确保没有写入SD内容)。

继SO咨询( 12 )我能处理SIGTERM如果我手动杀进程(即杀{进程号}),但如果我发送关机命令(即关机-t 30现在 )我的处理程序不会被调用。

我也尝试注册所有信号并检查在关闭事件上发送的信号,但没有收到任何信号。

这是简单的示例代码:

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)

任何想法将不胜感激.. =)

这段代码在树莓派上对我有用,重新启动后,我可以在文件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脚本之前处理信号,所以您实际上看不到任何东西。 尝试查看文件中的输出(使用日志记录模块或您喜欢的方式)。

暂无
暂无

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

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