signal_safety

signal safety is more restrict than thread safety.

. If you see a function documented as being "thread safe", you know that you can call it simultaneously from multiple threads. If you see a function documented as being "async-signal safe", then you know that you can call it from a signal handler without blowing up your program. A fairly complete list of signal safe functions can be found in man sigaction.

Self pipe:

volatile sig_atomic_t gReloadConfigFile = 0;

void handler(int signal) {
    gReloadConfigFile = 1;
}
...
while(!done) {
    if(gReloadConfigFile) {
        gReloadConfigFile = 0;
        ReloadConfigFile();
    }
    // X
    select(...);
    ProcessData(...);
}

If your program is blocked in the select(), the signal will dislodge it and the app will reload its configuration file. If the program is busy processing data when it comes in, then the configuration file will be reloaded before you get back to the select(). But… you guessed it! This code isn't completely safe!
The key is the // X comment. If the signal is delivered in that spot, after the check but before entering the select(), the select() will still block, and the configuration file won't be reloaded until some input arrives, which could be much later.
The best way is to use a signaling mechanism which can be integrated into the select() call, namely a pipe. You can create a pipe using the pipe() system call, then read from it in the select() and write to it in your signal handler.

From signal safety

reentrant v.s thread-safe v.s async-signal-safe

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License