7

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;
}
cong
  • 1,105
  • 1
  • 12
  • 29

1 Answers1

7

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.

Mark Plotnick
  • 9,598
  • 1
  • 24
  • 40
  • 3
    Why don't nearly all signal handlers save errno and restore it in single thread process? Because these programmers just don't take this into consideration? – cong Feb 01 '18 at 03:16
  • 1
    In addition the man page signal-safety(7) says this: "Fetching and setting the value of errno is async-signal-safe provided that the signal handler saves errno on entry and restores its value before returning." – penguin359 Dec 11 '21 at 01:59