3 ms·
The worst thing about signals is that they interrupt whatever system call the thread is currently inside (EINTR). This is not typically observed but can have di
by ambrop7 10y ago
The worst thing about signals is that they interrupt whatever system call the thread is currently inside (EINTR). This is not typically observed but can have dire consequences randomly. For example, last time I checked, in Python 2.7, a signal that invoked a signal handler will cause a running print() to throw an exception. Here you should consider signals like SIGCHLD which you want to handle and not kill the process.
A particular case this happens is when doing event-driven programming. The only way to be sure that you don't have such bugs lurking is to setup signal handling such that a signal cannot possibly interrupt unsuspecting code. Currently, I'm aware of two solutions, both involve blocking signals:
1. Block relevant signals in the main loop (or generally all threads) and use signalfd to detect and consume signals (or similar mechanisms on other platforms, e.g. kqueue).
2. Start a dummy thread whose only purpose is to handle signals, leave relevant signals unblocked in this thread and block them in all other threads. Write the signal handler to communicate the signal to your main loop via the self-pipe mechanism or similar.
Note that solution (2) can usually be implemented for an existing framework without changing that framework - you only need to add code to main which starts that thread then blocks signals, before any other threads are started.
I consider "fixing" code to be robust to signals a non-solution, because you would have to verify every single piece of code running in your program, including third-party libraries.
- ptx 10y ago> For example, last time I checked, in Python 2.7, a signal that invoked a signal handler will cause a running print() to throw an exception. Python 3.5 fixes this – system calls are now automatically retried: https://docs.python.org/3.5/whatsnew/3.5.html#pep-475-retry-system-calls-failing-with-eintr https://docs.python.org/3.5/whatsnew/3.5.html#pep-475-retry-...