python如何处理信号? [英] How does python process a signal?

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

问题描述

在python中处理信号的工作流程是什么?我设置了一个信号处理程序,当信号出现时,python如何调用我的函数?操作系统是否像C程序一样调用它?如果我在python的C扩展中,它会立即中断吗?

What is the workflow of processing a signal in python ? I set a signal handler, when the signal occur ,how does python invoke my function? Does the OS invoke it just like C program? If I am in a C extend of python ,is it interrupted immediately ?

现在我很清楚python进程如何处理信号.当您通过信号模块设置信号时,该模块将注册一个signal_handler函数(请参阅$ src/Modules/signalmodule.c),该函数会设置您的处理程序并将其标记为1( Handlers [sig_num] .tripped = 1; ),然后调用Py_AddPendingCall告诉python解释器.python解释器将调用Py_MakePendingCalls来调用PyErr_CheckSignals,后者在主循环中调用您的函数(请参见$ src/Python/ceval.c).如果您想谈论这个问题,请与我联系:renenglish@gmail.com

Now it's clear to me how does python process handle a signal . When you set a signal by the signal module , the module will register a function signal_handler(see $src/Modules/signalmodule.c) ,which set your handler and flag it as 1(Handlers[sig_num].tripped = 1;) , then call Py_AddPendingCall to tell python interpreter. The python interpreter will invoke Py_MakePendingCalls to call PyErr_CheckSignals which calls your function in main loop(see $src/Python/ceval.c). communicate me if you want to talk about this : renenglish@gmail.com

推荐答案

如果您使用信号模块设置了Python代码信号处理程序,则解释器仅在重新输入字节码解释器时才运行它.处理程序不会立即运行.发生信号时将其放在队列中.如果代码路径当前位于C代码,内置模块或扩展模块中,则将处理程序推迟到C代码将控制权返回给Python字节代码解释器之前.这可能会很长一段时间,您无法真正预测会持续多长时间.

If you set a Python code signal handler using the signal module the interpreter will only run it when it re-enters the byte-code interpreter. The handler is not run right away. It is placed in a queue when the signal occurs. If the code path is currently in C code, built-in or extension module, the handler is deferred until the C code returns control to the Python byte code interpreter. This can be a long time, and you can't really predict how long.

最显着的一点是,如果您使用启用了readline的交互模式,则在您提供一些信号解释之前,信号处理程序将不会运行.这是因为输入代码在readline库(C代码)中,并且直到有完整的行才返回到解释器.

Most notably if you are using interactive mode with readline enabled your signal handler won't run until you give it some input to interpret. this is because the input code is in the readline library (C code) and doesn't return to the interpreter until it has a complete line.

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

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