如何正确处理和保留系统关闭(和 SIGTERM)以完成其在 Python 中的工作? [英] How to properly handle and retain system shutdown (and SIGTERM) in order to finish its job in Python?

查看:31
本文介绍了如何正确处理和保留系统关闭(和 SIGTERM)以完成其在 Python 中的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本需求:我有一个 Python 守护进程,它通过 os.system 调用另一个程序.我的愿望是能够正确处理系统关闭或SIGTERM,以便让被调用的程序返回然后退出.

Basic need : I've a Python daemon that's calling another program through os.system. My wish is to be able to properly to handle system shutdown or SIGTERM in order to let the called program return and then exiting.

我已经尝试过的:我已经尝试过使用信号的方法:

What I've already tried: I've tried an approach using signal :

import signal, time

def handler(signum = None, frame = None):
    print 'Signal handler called with signal', signum
    time.sleep(3)
    #here check if process is done
    print 'Wait done'

signal.signal(signal.SIGTERM , handler)

while True:
    time.sleep(6)

time.sleep 的用法似乎不起作用,并且永远不会调用第二次打印.

The usage of time.sleep doesn't seems to work and the second print is never called.

我读了几篇关于 atexit.register(handler) 而不是 signal.signal(signal.SIGTERM, handler) 的文字,但没有调用 kill .

I've read few words about atexit.register(handler) instead of signal.signal(signal.SIGTERM, handler) but nothing is called on kill.

推荐答案

你的代码几乎可以工作,只是你在清理后忘记退出.

Your code does almost work, except you forgot to exit after cleaning up.

我们经常需要捕获各种其他信号,例如 INT、HUP 和 QUIT,但使用守护进程则不需要那么多.

We often need to catch various other signals such as INT, HUP and QUIT, but not so much with daemons.

import sys, signal, time

def handler(signum = None, frame = None):
    print 'Signal handler called with signal', signum
    time.sleep(1)  #here check if process is done
    print 'Wait done'
    sys.exit(0)

for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]:
    signal.signal(sig, handler)

while True:
    time.sleep(6)

在许多系统上,普通进程在关机期间没有太多时间进行清理.为安全起见,您可以编写一个 init.d 脚本来停止您的守护进程并等待它.

On many systems, ordinary processes don't have much time to clean up during shutdown. To be safe, you could write an init.d script to stop your daemon and wait for it.

这篇关于如何正确处理和保留系统关闭(和 SIGTERM)以完成其在 Python 中的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆