处理同一个错误时多次调用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/