python如何处理信号?
python 中处理信号的工作流程是怎样的?我设置了一个信号处理程序,当信号发生时,python如何调用我的函数?操作系统是否像C程序一样调用它? 如果我在 python 的 C 扩展中,它会立即中断吗?
现在我清楚了 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)。 如果您想讨论此问题,请与我联系:[电子邮件受保护]
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 ?
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 : [email protected]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用信号模块设置Python代码信号处理程序,解释器只会在重新进入字节码解释器时运行它。处理程序不会立即运行。当信号发生时,它被放入队列中。如果代码路径当前位于 C 代码、内置或扩展模块中,则处理程序将被推迟,直到 C 代码将控制权返回给 Python 字节代码解释器。这可能是很长一段时间,你无法真正预测多久。
最值得注意的是,如果您使用启用了 readline 的交互模式,您的信号处理程序将不会运行,直到您给它一些输入来解释。这是因为输入代码位于 readline 库(C 代码)中,并且在具有完整行之前不会返回到解释器。
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.
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 脚本调用信号,根据我的理解,如果有处理程序,它将首先处理该信号,并且可能具有处理和忽略某些信号的能力。 IE。您尝试在终止之前执行一些关闭清理工作,而不是在 SIGKILL 上终止。
Take a look at the signal module. If you invoke a signal to a python script, from my understanding if there is a handler for it will first process that signal, and potentially has the ability to handle and ignore certain signals. ie. instead of killing on a SIGKILL, you attempt to perform some shutdown cleanup work before killing.