Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trapping signals in Python

Tags:

python

signals

According to the documentation:

There is no way to “block” signals temporarily from critical sections (since this is not supported by all Unix flavors).

What stops me using signal.signal(signum,SIG_IGN) to block it, then adding the signal back?

like image 354
Casebash Avatar asked Jan 01 '26 18:01

Casebash


1 Answers

What stops you is that, if the signal actually arrives while SIG_IGN is in place, then it will be ignored and thrown away. When you add the signal back later, it's too late because it's gone and you'll never get to learn that it happened.

Thus, you will have "ignored" (= thrown away) the signal rather than "blocked" it (= kept it for handling at the end of the critical section). Your confusion here might just arise from not knowing specifically what "blocking" a signal means: it means the OS hangs onto the signal, letting it wait to strike until your critical section is complete.

See (as a great reference for all sorts of questions like this) W. Richard Steven's Advanced Programming in the UNIX Environment. Section 10.8 in the edition I have, "Reliable Signal Terminology and Semantics", is the one I just checked before answering to be sure of my answer.

Update: on my Ubuntu laptop, "man sigprocmask" (if manpages-dev is installed) seems to be the man page to start with for learning about signal blocking. Again, as the Python docs note, this isn't available under all Unixes, so don't expect your old Irix or AIX box to run your Python program if you actually use "sigprocmask". But maybe you're not worried about that. :-)

like image 132
Brandon Rhodes Avatar answered Jan 03 '26 07:01

Brandon Rhodes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!