Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: Can a signal handler excution be preempted?

I came across the following signal handler code that stores the errno variable so that it wont affect main thread's errno handling.

void myhandler(int signo)
{
    int esaved;
    esaved = errno;
    write(STDOUT_FILENO, "Got a signal\n", 13);
    errno = esaved;
}

But this really serves the purpose ? what happens if another thread check for the shared errno varible just after write() and before restoring errno ? Will that thread get wrong errno value due to race condition?

Or a signal handler executes atomically with respect to a thread/process, so that once the signal handler executes , kernel wont schedule the thread back until the signal handler finishes?

Putting in other words -Once started, do a signal handler executes without being interrupted by:

 - 1) Scheduler (process/threads),  or  
 - 2) Other signals,  or
 - 3) Hardware interrupt handlers  ?
like image 898
Lunar Mushrooms Avatar asked Dec 16 '22 12:12

Lunar Mushrooms


1 Answers

The signal handler can indeed be interrupted by another signal (assuming it isn't the same signal as the one which invoked the handler in the first place).

your handler can still be interrupted by delivery of another kind of signal. To avoid this, you can use the sa_mask member of the action structure passed to sigaction to explicitly specify which signals should be blocked while the signal handler runs. These signals are in addition to the signal for which the handler was invoked, and any other signals that are normally blocked by the process. See Blocking for Handler.

When the handler returns, the set of blocked signals is restored to the value it had before the handler ran. So using sigprocmask inside the handler only affects what signals can arrive during the execution of the handler itself, not what signals can arrive once the handler returns.

http://www.gnu.org/software/libc/manual/html_node/Signals-in-Handler.html#Signals-in-Handler

like image 199
kronion Avatar answered Dec 28 '22 09:12

kronion