Wednesday 15 September 2010

python - Alarm signal not firing in infinite loop -



python - Alarm signal not firing in infinite loop -

i'm trying timeout function if runs more 3 seconds (for example). i'm using signals , alarms alarm never fires. i'd timeout mechanism works function. illustration of problem i'm facing:

import signal def foobar(): x = 42 while x >= 20: if x >= 40: x = 23 homecoming x def handle_alarm(*args): print("alarm raised") raise timeoutexception("timeout reached") signal.signal(signal.sigalrm, handle_alarm) signal.alarm(3) try: print(foobar()) except: print("exception caught")

when run, programme runs forever , handler never runs. thought why case?

as aside, if delete if statement foobar, alarm trigger.

on system, mac os x macports, tested code many version of python. version exhibits "bug" found 2.7. timeout works in 2.4, 2.5, 2.6, 3.3, , 3.4.

now, why happening, , can done it?

i think happens because foobar() tight loop never "yields" command python's main loop. runs fast can, doing no useful work, yet preventing python processing signal.

it help understand how signals in *nix handled. since few library functions "async signal safe," not much can done within c signal handler directly. python needs invoke signal handler written in python, can't straight in signal handler registers using c. typical thing programs in signal handlers set flag indicate signal has been received, , return. in main loop, then, flag checked (either straight or using "pipe" can written in signal handler , poll()ed or select()ed on).

so suppose python main loop happily executing foobar() function, , signal comes in, sets internal state know needs handle signal, , waits for foobar() end, or failing that, @ to the lowest degree foobar() invoke interruptible function, such sleep() or print().

and indeed, if add together either sleep (for amount of time), or print statement foobar()'s loop, timeout want in python 2.7 (as other versions).

it in general thought set short sleep in busy loops anyway, "relax" them, thereby helping scheduling of other work may need doing. don't have sleep on every iteration either--just tiny sleep every 1000 times through loop work fine in case.

python python-2.7

No comments:

Post a Comment