Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 592
cong Avatar asked Jan 22 '18 09:01

cong


1 Answers

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.

like image 53
Mark Plotnick Avatar answered Oct 05 '22 18:10

Mark Plotnick