Python信号处理

2024-04-28 16:23:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我安装了^{},现在我正在尝试正确地处理信号。我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import signal, time, syslog
import daemon

def runDaemon():
    context = daemon.DaemonContext()

    context.signal_map = { signal.SIGTERM: programCleanup }

    context.open()
    with context:
        doMainProgram()

def doMainProgram():
    while True:
        syslog.syslog("pythonDaemon is running")
        time.sleep(5)

def programCleanup():
    syslog.syslog("pythonDaemon STOP")

if __name__ == "__main__":
    runDaemon()

当我启动代码时,一切都按预期工作:pythonDaemon运行的文本每5秒就被写入/var/log/syslog。 但是当我想用kill -TERM *PID*终止守护进程时,守护进程被终止,但是syslog中缺少文本pythonDaemon STOP。在

我做错什么了?在

注意:我不在这里使用from daemon import runner,因为这给了我一个错误(看起来我需要一个旧版本的lockfile),我不会修复这个问题,除非这是唯一可能得到正确的信号处理。在


Tags: 代码文本importsignaltime进程defcontext
1条回答
网友
1楼 · 发布于 2024-04-28 16:23:18

您的代码看起来很好,只是没有调用信号处理程序,因为它有错误的签名。这样做:

def programCleanup(signum, frame):

引用文件(signal.signal()):

The handler is called with two arguments: the signal number and the current stack frame

相关问题 更多 >