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));
}
Run Code Online (Sandbox Code Playgroud)
errno的值只能在调用明确声明为其设置的函数之后定义,并且直到它被下一个函数调用更改或者应用程序为其赋值.
http://www.opengroup.org/onlinepubs/009695399/functions/errno.html
但是,strerror理论上甚至可以将其视为可以改变它的函数调用(请参阅schot的注释),因此理论上,您应该使用保存优先形式.