signal.alarm 未按时触发异常 [英] signal.alarm not triggering exception on time

查看:37
本文介绍了signal.alarm 未按时触发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我稍微修改了官方文档(页面底部).

I've slightly modified the signal example from the official docs (bottom of page).

我正在呼叫 sleep 10 但我希望在 1 秒后发出警报.当我运行以下代码段时,触发异常需要 1 秒以上的时间(我认为它运行了整整 10 秒).

I'm calling sleep 10 but I would like an alarm to be raised after 1 second. When I run the following snippet it takes way more than 1 second to trigger the exception (I think it runs the full 10 seconds).

import signal, os

def handler(signum, frame):
    print 'Interrupted', signum
    raise IOError("Should after 1 second")

signal.signal(signal.SIGALRM, handler)
signal.alarm(1)

os.system('sleep 10')

signal.alarm(0)

如何确保在单线程应用程序超时后终止函数?

How can I be sure to terminate a function after a timeout in a single-threaded application?

推荐答案

来自 文档:

Python 信号处理程序不会在低级 (C) 中执行信号处理程序.相反,低级信号处理程序设置一个标志它告诉虚拟机执行相应的 Python稍后的信号处理程序(例如在下一个字节码说明).

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).

因此,在某些情况下,signal.alarm() 生成的信号无法在超时后终止函数.该函数应该通过允许其他 Python 代码运行来协作(例如,通过在 C 中定期调用 PyErr_CheckSignals()代码),或者您应该使用单独的进程,及时终止函数.

Therefore, a signal such as that generated by signal.alarm() can't terminate a function after a timeout in some cases. Either the function should cooperate by allowing other Python code to run (e.g., by calling PyErr_CheckSignals() periodically in C code) or you should use a separate process, to terminate the function in time.

如果您使用 subprocess.check_call('sleep 10'.split()) 而不是 os.system('sleep 10'),则可以修复您的情况.

Your case can be fixed if you use subprocess.check_call('sleep 10'.split()) instead of os.system('sleep 10').

这篇关于signal.alarm 未按时触发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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