当函数返回时停止 SIGALRM [英] Stop SIGALRM when function returns

查看:60
本文介绍了当函数返回时停止 SIGALRM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我自己似乎无法解决的问题.我正在编写一个小的 python 脚本,我想知道为什么我的 signal.alarm 在它所在的函数返回后仍然有效.代码如下:

I have a problem that I can't seem to solve by myself. I'm writing a small python script and I would like to know why my signal.alarm still works after the function it's located in returned. Here is the code:

class AlarmException(Exception):
    pass

def alarmHandler(signum, frame):
    raise AlarmException

def startGame():
    import signal
    signal.signal(signal.SIGALRM, alarmHandler)
    signal.alarm(5)
    try:
        # some code...
        return 1
    except AlarmException:
        # some code...
        return -1

def main():
    printHeader()
    keepPlaying = True
    while keepPlaying:
        score = 0
        for level in range(1):
            score += startGame()
        answer = raw_input('Would you like to keep playing ? (Y/N)\n')
        keepPlaying = answer in ('Y', 'y')

所以问题是当我的 startGame() 函数返回时,SIGALRM 仍在倒计时并关闭我的程序.这是回溯:

So the problem is that when my startGame() function returns, the SIGALRM is still counting down and shutdown my program. Here is the traceback:

Would you like to keep playing ? (Y/N)
Traceback (most recent call last):
  File "game.py", line 84, in <module>
    main()
  File "game.py", line 80, in main
    answer = raw_input('Would you like to keep playing ? (Y/N)\n')
  File "game.py", line 7, in alarmHandler
    raise AlarmException
__main__.AlarmException

当它所在的函数退出时,我如何继续告诉 SIGALRM 停止?

How can I proceed to say to SIGALRM to stop when the function it is in has exited ?

谢谢!

推荐答案

当你想禁用闹钟时,尝试调用 signal.alarm(0).

Try calling signal.alarm(0) when you want to disable the alarm.

很可能它只是在 libc 中调用 alarm(),而 man alarmalarm(0) "...使当前警报无效,并且不会传递信号 SIGALRM."

In all likelyhood it just calls alarm() in libc, and the man alarm says that alarm(0) "... voids the current alarm and the signal SIGALRM will not be delivered."

这篇关于当函数返回时停止 SIGALRM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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