c - 是否要避免连续调用 `errno`?

标签 c

处理同一个错误时多次调用errno是否安全。还是使用本地副本更安全?

这个示例说明了我的问题:

// If recvfrom() fails it returns -1 and sets errno to indicate the error.
int res = recvfrom(...);
if (res < 0)
{
    // Risky?
    printf("Error code: %d. Error message: %s\n", errno, strerror(errno));

    // Safer alternative?
    int errorNumber = errno;
    printf("Error code: %d. Error message: %s\n", errorNumber, strerror(errorNumber));
}

最佳答案

The value of errno shall be defined only after a call to a function for which it is explicitly stated to be set and until it is changed by the next function call or if the application assigns it a value.

http://www.opengroup.org/onlinepubs/009695399/functions/errno.html

但是,即使 strerror 理论上也可以算作可以更改它的函数调用(请参阅 schot 的评论),因此从理论上讲,您仍然应该使用先保存的形式。

关于c - 是否要避免连续调用 `errno`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3870365/

相关文章:

c - modf函数intpart为零?

c - libssh - 无法连接到本地主机

C语言计算文件行数

c - 使用 == 进行字符串比较

c - 反转字符串时交换指针值时出现段错误

c - 我的 "won"函数有什么问题

c - 声明包含指针的全局结构

c - 为什么 sizeof 没有给出数组的长度?

c - 尽管定义为 1,变量值仍然过长

c - 小代码段错误