gpt4 book ai didi

python - 如何从运行 pyzmq 的进程捕获 SIGERM、SIGINT?

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:12 25 4
gpt4 key购买 nike

我正在使用 PYZMQ,似乎我无法再捕获 SIGTERM。如何优雅地处理 SIGTERM ?

下面是代码片段:

from time import sleep
from signal import signal, SIGTERM, SIGINT
from threading import Lock, Thread
try:
import cPickle as pickle
except ImportError:
import pickle
import zmq


zmq_poller = None

class server(Thread, object):
def __init__(self, transport):
self.context = zmq.Context()
self.zmq_socket = self.context.socket(zmq.PULL)
self.zmq_socket.setsockopt(zmq.RCVTIMEO, 2000)
self.zmq_socket.bind(transport)
self.keep_running = True
Thread.__init__(self)

def process_data(self, data):
data = self.decode(data)

def decode(self, data):
return pickle.loads(data)

def run(self):
while self.keep_running:
try:
data = self.zmq_socket.recv()
self.process_data(data)
except zmq.error.Again:
pass
except zmq.error as e:
print e

def stop(self):
self.keep_running = False

def handle_stop(signum=None, frame=None):
if zmq_poller:
zmq_poller.stop()

if __name__ == '__main__':
signal(SIGTERM, handle_stop)
signal(SIGINT, handle_stop)
mc = server('ipc:///tmp/abc')
zmq_poller = mc
mc.setDaemon(True)
mc.start()
mc.join()
sleep(100)

正如我们所见,如果我向进程发送 SIGTERM、SIGINT,则不会调用 handle_stop 信号处理程序

最佳答案

问题的原因是您的主线程被 threading.Thread.join Execution of Python signal handlers 阻塞。 :

A Python signal handler does not get executed inside the low-level (C) signal handler. Instead, the low-level signal handler sets a flag which tells the virtual machine to execute the corresponding Python signal handler at a later point(for example at the next bytecode instruction)

A long-running calculation implemented purely in C (such as regular expression matching on a large body of text) may run uninterrupted for an arbitrary amount of time, regardless of any signals received. The Python signal handlers will be called when the calculation finishes.

在 3.3 之前,signal 模块绝对不会公开您自己解决此问题所需的工具。因此,如果您无法升级到 3.3,解决方案是等待可中断的事件,例如 ConditionEvent。子线程在退出之前通知该事件,主线程在加入子线程之前等待该事件。

关于python - 如何从运行 pyzmq 的进程捕获 SIGERM、SIGINT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31823475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com