I know many questions have been asked previously about error handling in C but this is specifically about errno stuff.
I want to ask whether we should use the errno/perror functionality to handle errors gracefully at runtime.I am asking this because MSVC uses it and Win32 api also uses it heavily.I don’t know anything about gcc or ‘linux api’.Today both gcc and MSVC say that errno/perror can be used safely in a multithreaded environment.So what’s your view?
thanks.
Note that using
errnoalone is a bad idea: standard library functions invoke other standard library functions to do their work. If one of the called functions fails,errnowill be set to indicate the cause of the error, and the library function might still succeed, if it has been programmed in a manner that it can fall back to other mechanisms.Consider
malloc(3)— it might be programmed to trymmap(.., MAP_PRIVATE|MAP_ANONYMOUS)as a first attempt, and if that fails fall back tosbrk(2)to allocate memory. Or considerexecvp(3)— it may probe a dozen directories when attempting to execute a program, and many of them might fail first. The ‘local failure’ doesn’t mean a larger failure. And the function you called won’t seterrnoback to0before returning to you — it might have a legitimate but irrelevant value left over from earlier.You cannot simply check the value of
errnoto see if you have encountered an error.errnoonly makes sense if the standard library function involved also returned an error return. (Such asNULLfromgetcwd(3)or-1fromread(2), or “a negative value” fromprintf(3).)But in the cases when standard library functions do fail,
errnois the only way to discover why they failed. When other library functions (not supplied by the standard libraries) fail, they might useerrnoor they might provide similar but different tools (see e.g.ERR_print_errors(3ssl)orgai_strerror(3).) You’ll have to check the documentation of the libraries you’re using for full details.