linuxsignalssignal-handling

How to deal with errno and signal handler in Linux?


When we write a signal handler that may change the errno, should we save errno at the beginning of the signal handler and restore the errno at the end of it? Just like below:

void signal_handler(int signo){
    int temp_errno = errno;
    *** //code here may change the errno
    errno = temp_errno;
}

Solution

  • The glibc documentation says:

    signal handlers that call functions that may set errno or modify the floating-point environment must save their original values, and restore them before returning.

    So go ahead and do that.

    If you're writing a multi-threaded program using pthreads, there's a workaround that requires less effort. errno will be in thread-local storage. If you dedicate one thread to handle process-directed signals, blocking the signal in all other threads, you don't have to worry about assignments to errno in the signal handler.