如何处理Linux中的errno和signal handler?

How to deal with errno and signal handler in Linux?

当我们写一个可能改变errno的信号处理程序时,我们是否应该在信号处理程序的开头保存errno并在它的结尾恢复errno?就像下面这样:

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

glibc 文档 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.

所以继续吧。

如果您正在使用 pthreads 编写多线程程序,则有一种解决方法需要更少的努力。 errno 将在线程本地存储中。如果你专门用一个线程来处理进程导向的信号,阻塞所有其他线程中的信号,你就不必担心信号处理程序中对 errno 的赋值。