Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop SIGALRM when function returns

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

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

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

Thanks !

like image 1000
Oscar Avatar asked Nov 19 '14 09:11

Oscar


People also ask

How do you disable a signal alarm in Python?

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

What does alarm () do in C?

The alarm() function shall cause the system to generate a SIGALRM signal for the process after the number of realtime seconds specified by seconds have elapsed. Processor scheduling delays may prevent the process from handling the signal as soon as it is generated.

What is signal pause?

signal. pause() Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing. Availability: Unix.

What is SIGALRM C?

SIGALRM is an asynchronous signal. The SIGALRM signal is raised when a time interval specified in a call to the alarm or alarmd function expires. Because SIGALRM is an asynchronous signal, the SAS/C library discovers the signal only when you call a function, when a function returns, or when you issue a call to sigchk .


1 Answers

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

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

like image 160
ErikR Avatar answered Oct 20 '22 02:10

ErikR