1

I came across this answered post that seems to indicate closures installed as signal handlers should capture their environment, however I'm not seeing that (using Python 2.7). For example:

import os
import signal
import time

if __name__ == "__main__":
    pid = os.fork()
    if pid:
        signal.pause()
    else:
        sigint = False

        def handler(s, f):
            # global sigint
            print "sigint: {}".format(sigint)
            print "Signal handler"
            sigint = True

        signal.signal(signal.SIGINT, handler)

        signal.pause()
        if sigint:
            print "Caught sigint, sleeping briefly"
            time.sleep(2)
        print "exiting..."

Which running and triggering with ^C raises UnboundedLocalError: local variable 'sigint' referenced before assignment in the child. Uncommenting the global declaration fixes this. Clearly this is at odds with the aforementioned post, is the previous post simply incorrect, or am I doing something wrong here?

EDIT: Also the forking here is entirely extraneous, I was intending to investigate a different behavior when I noticed this one and just took the little script verbatim. The else block can replace the entire main thread to achieve the same result.

Community
  • 1
  • 1
jot
  • 41
  • 1
  • 4
  • What is the argument s in the handler? – fiacre Mar 23 '17 at 15:58
  • @fiacre just placeholders for the standard signal handler arguments. Python signal handlers are always passed `signum, frame` by default, specifying the signal which triggered that handler and the call stack frame which was interrupted. I don't use either here and got tired of writing out "signum, frame" over and over. – jot Mar 23 '17 at 16:20
  • that's my point, if the signal's number is being sent as an argument, why are you defining it outside the handler? – fiacre Mar 23 '17 at 18:21
  • @fiacre The `sigint` variable is simply a flag to indicate that the handler has been invoked. It has nothing to do with the signal number. I could name it `foobar` to the same effect. – jot Mar 23 '17 at 21:47

0 Answers0