Is it safe to call errno
multiple times when dealing with the same error. Or is it safer to work with a local copy?
This sample illustrates my question:
// 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));
}
Initializing ErrnoYour program should always initialize errno to 0 (zero) before calling a function because errno is not reset by any library functions. Check for the value of errno immediately after calling the function that you want to check. You should also initialize errno to zero after an error has occurred.
The main reason for using errno is to give more information about the error condition. This is especially useful in situations where most (or even all) possible return values of a function are actually valid return values. Consider the fopen() function, which returns a pointer to a FILE .
python-filenotfounderror. In most cases, any file you reference in a Python program needs to exist. This is, of course, unless you are creating a new file and writing to it. If you reference a file that does not exist, Python will return an error.
EINTR is the error which so-called interruptible system calls may return. If a signal occurs while a system call is running, that signal is not ignored. If a signal handler was defined for it without SA_RESTART set and this handler handles that signal, then the system call will return the EINTR error code.
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
However, even strerror
could theoretically count as a function call that can change it (see comment by schot) so you should, theoretically, still go with your save-first form.
Any standard library function including printf and strerror is allowed to change errno, even if actually no error occurs:
7.5 3 The value of errno is zero at program startup, but is never set to zero by any library function. 170) The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in this International Standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With