在Linux中如何处理errno和信号处理程序? [英] How to deal with errno and signal handler in Linux?

查看:116
本文介绍了在Linux中如何处理errno和信号处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们编写一个可能更改errno的信号处理程序时,是否应该在信号处理程序的开头保存errno并在其末尾恢复errno?如下所示:

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

推荐答案

glibc文档 调用可能设置errno或修改浮点环境的函数的

信号处理程序必须保存其原始值,并在返回之前将其还原.

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将位于线程本地存储中.因此,您可以专门使用一个线程来处理信号,并在所有其他线程中阻止该信号.

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.

这篇关于在Linux中如何处理errno和信号处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆