How to deal with errno and signal handler in Linux

2019-05-11 16:58发布

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;
}

1条回答
Fickle 薄情
2楼-- · 2019-05-11 17:02

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.

To those reading this who can't rewrite their signal handlers, there may be a workaround. If you're writing a multi-threaded program using pthreads, errno will be in thread-local storage. So you can possibly dedicate one thread to handle a signal and block the signal in all other threads.

查看更多
登录 后发表回答