Handling signals in Linux with C++
Why signals are important
Signals are the simplest form of IPC in Unix-like systems. They are notifiers to the process that an external event has happened. As this is a system specific mechanism, there’s no portable C++ STL library providing support for signal handling. But it’s fairly easy to write one. First though a short introduction is required.
Signal disposition
Each thread in a process has a signal mask which can be modified either via
setprocmask
(for single threaded processes) or pthread_sigmask
(for
multithreaded processes). Every raised signal is checked against the mask. If
it’s blocked, it’s residing in a PENDING state and it will be immediately
handled once unblocked. If it’s not blocked, its corresponding signal handler
will be called or the default action executed in case there is none. Of course
there are signals which can’t be blocked or its disposition can’t be altered
(like SIGKILL or SIGSTOP). In other words, pending signal is handled as
soon as thread’s signal mask unblocks it. It’s also worth to remember that
signals are not queued (aside from realtime signals - these are queued).
Multiple subsequently raised pending signals will be handled as if a single
one was raised.