【问题标题】:SIGTERM signal not received by python on shutdown commandpython 在关闭命令时未收到 SIGTERM 信号
【发布时间】:2014-06-09 20:14:42
【问题描述】:

几个月来,我一直在为 raspberryPi 使用 python 进行编程,我正试图让我的脚本“表现良好”并在收到 SIGTERM 后结束(关闭文件并确保没有写入 SD)。

遵循关于 SO (1, 2) 的建议,如果我手动终止进程(即 kill {process number}),我可以处理 SIGTERM,但如果我发送关闭命令(即 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)

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

【问题讨论】:

  • 有可能在shutdown 上得到SIGTERM,但脚本无法输出到屏幕。追加到日志文件,然后在机器恢复时检查日志。
  • 好点。我会尝试并报告我的发现
  • @shavenwarthog:当我尝试使用-t 使用shutdown 命令时(据我所知是SIGTERMSIGKILL 之间的时间),我可以配置合理的时间查看屏幕的输出。无论如何是一个有效的观点。

标签: python signals raspberry-pi raspbian


【解决方案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 脚本之前处理了信号,所以你实际上看不到任何东西。尝试查看文件中的输出(使用日志记录模块或您喜欢的方式)。

【讨论】:

    猜你喜欢
    • 2013-06-05
    • 2018-04-28
    • 2021-01-29
    • 2021-11-23
    • 2021-05-22
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多