65 points · by hellerve · 3mo ago · 35 comments
Python or not, almost nothing is safe inside a signal handler.
That's a bit of an overstatement? There's a list of things that you _can_ call, and fairly useful ones too like `write`
If the signal occurs other than as the result of calling abort(), raise(),
[CX] [Option Start] kill(), pthread_kill(), or sigqueue(), [Option End] the
behavior is undefined if the signal handler refers to any object with static
storage duration other than by assigning a value to an object declared as
volatile sig_atomic_t, or if the signal handler calls any function in the
standard library other than one of the functions listed in Signal Concepts.
You literally can't read any global/static variables and you can only write to global/static variables that are declared to be volatile sig_atomic_t. This tremendously shrinks the amount of useful work you can do with the signal-safe functions from the standard library.The ones related to application logic must only be handled with signalfd if you want any semblance of reliability.
The other one that plays nicely with threads is blocking the signals everywhere with pthread_sigmask and parking one dedicated thread in sigwait(). Both are in the stdlib on Unix.
signalfd is nicer than either but it's Linux only, which is why set_wakeup_fd usually wins if you care about portability.
If your program generates signals, it could generate a flood unintentionally. If you put a print statement in the handler, you can get this result.
It's not terribly surprising, but good to know.
The C printf function is not async signal safe and is one of the examples in the manual: https://man7.org/linux/man-pages/man7/signal-safety.7.html