Python中的信号处理 [英] Signal handling in Python

查看:40
本文介绍了Python中的信号处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我有一堆线程在运行,我正在尝试中断主线程以使其异步执行某些操作.所以我设置了一个处理程序并向主进程发送一个 SIGUSR1 - 查看代码下面:

In my program I have a bunch of threads running and I'm trying to interrupt the main thread to get it to do something asynchronously. So I set up a handler and send the main process a SIGUSR1 - see the code below:

def SigUSR1Handler(signum, frame):

    self._logger.debug('Received SIGUSR1')

    return

signal.signal(signal.SIGUSR1, SigUSR1Handler)

[signal.signal(signal.SIGUSR1, signal.SIG_IGN)]

在上面的例子中,所有的线程和主进程都停止了——从一个 'c'观点这是出乎意料的 - 我希望线程继续在信号之前.如果我把 SIG_IGN 放进去,一切都会继续很好.

In the above case, all the threads and the main process stops - from a 'c' point of view this was unexpected - I want the threads to continue as they were before the signal. If I put the SIG_IGN in instead, everything continues fine.

谁能告诉我怎么做?也许我必须对框架"做些什么手动回到原来的位置..只是一个猜测提前致谢,

Can somebody tell me how to do this? Maybe I have to do something with the 'frame' manually to get back to where it was..just a guess though thanks in advance,

感谢您对此的帮助.

再解释一下,我有线程实例将字符串信息写入一个也输出到文件的套接字.这些线程运行自己的计时器,因此它们独立地将它们的输出写入套接字.当程序运行时,我也看到他们在标准输出上的输出,但一旦我看到信号中的调试行,它就会停止.

To explain a bit more, I have thread instances writing string information to a socket which is also output to a file. These threads run their own timers so they independently write their outputs to the socket. When the program runs I also see their output on stdout but it all stops as soon as I see the debug line from the signal.

我需要线程不断发送此信息,但我需要主程序接受一个命令,所以它也开始做其他事情(并行)一段时间.我以为我只能从命令行发送信号来触发它.

I need the threads to constantly send this info but I need the main program to take a command so it also starts doing something else (in parallel) for a while. I thought I'd just be able to send a signal from the command line to trigger this.

推荐答案

混合信号和线程总是有点不稳定.但是,您描述的情况不应该发生.Python 只在主线程中处理信号.如果操作系统将信号传递给另一个线程,该线程可能会被短暂中断(例如,在执行系统调用时),但不会执行信号处理程序.主线程将被要求在下一次机会执行信号处理程序.

Mixing signals and threads is always a little precarious. What you describe should not happen, however. Python only handles signals in the main thread. If the OS delivered the signal to another thread, that thread may be briefly interrupted (when it's performing, say, a systemcall) but it won't execute the signal handler. The main thread will be asked to execute the signalhandler at the next opportunity.

当您发送信号时,您的线程(包括主线程)实际上在做什么?你怎么注意到它们都停止"了?是短暂的停顿(很容易解释,主线程需要在处理信号之前获取 GIL)还是进程完全崩溃?

What are your threads (including the main thread) actually doing when you send the signal? How do you notice that they all 'stop'? Is it a brief pause (easily explained by the fact that the main thread will need to acquire the GIL before handling the signal) or does the process break down entirely?

这篇关于Python中的信号处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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