Synchronous signals vs. robust code

Donn Cave donn at
Mon Feb 18 06:26:52 CET 2002

Quoth Mark Mitchell <mark at>:
| This code is supposed to make sure that the file descriptors are
| not leaked; when we exit this scope, the descriptors will be closed,
| even if an exception occurs.  [Note that I am assuming that os.close
| will never thrown an exception when given a valid file descriptor.
| That's not strictly speaking true on some operating systems, but
| let's pretend that it is true.  For the purposes of this discussion,
| the particular functions involved don't matter.]

I guess it's just a matter of perspective, but instead of pretending
that close(2) would never throw an exception directly, I'd just as
soon imagine that it will.  If your object is to write very robust
code, that's the only tenable assumption, right?  The point of this
is to suggest that your problem with the finally: block isn't really
unique to programs that inflict signal handling on themselves, they're
just vulnerable in a particularly indiscriminate way.

The only thing I can suggest is nested finallys.

       # Do stuff with the pipe.
       # Close the ends of the pipe.

Elsewhere in your post you mention the possibility that a signal-raised
exception could abort the finally block before its first statement
executed.  I don't know either way, but my bet would be that the finally
block's first statement is guaranteed to start executing.

And of course if that's true, you could just use sigprocmask() as you
proposed to.  I don't recall what Python signal handling looks like
exactly, but I bet it would be worth looking at signalmodule.c before
you just write a simple wrapper around sigprocmask(), in case you need
to account for the latent signal that has been trapped by the interpreter
but not yet delivered to the handler.

If it isn't true (if an exception from a signal handler can interrupt a
finally block even before its first statement), then my preference would
be to get that fixed, rather than add provisions to finally just to account
for signal-handling folly.

	Donn Cave, donn at

More information about the Python-list mailing list