by nn3 · 3y ago · 0 comments
On contrary you should absolutely use errno, if only to report your IO errors.
Or maybe he never does IO. After all a program that doesn't output anything is likely safer, since these are all evil side effects. I can just see that new programming paradigm: "side effect free programming" taking over the world in storm.
Just based on that gaffe I'm not sure I can take anything else in that post seriously. It's clearly not based on any practical experience.
Errno is fine if you're accessing it right after a stdlib function that sets it, because it's the equivalent of a function's error code. Once you get out of that context errno becomes less and less useful and probably shouldn't be used, because without that context you won't know who/what actually set it.
“Previously both POSIX and X/Open documents were more restrictive than the ISO C standard in that they required errno to be defined as an external variable, whereas the ISO C standard required only that errno be defined as a modifiable lvalue with type int.”
Even now that it is guaranteed to be thread-local, it still is a bad API because of (same page)
“A program that uses errno for error checking should set it to 0 before a function call”
And yes, that still seems true today. https://en.cppreference.com/w/cpp/error/errno:
“library functions never store 0 in errno.”
It only happens to be implemented that way in some environments, as a macro to either thread local or some function call that retrieves the right errno.
Still, even that doesn't take care about signal handling.
errno = 0
// code which may error here
if(errno) { … }
And that errno is notably not scoped, so the code which may error should only be composed of calls to libc, or code whose interaction with libc you understand perfectly, otherwise you need to save and restore errno around uncontrolled calls.This is quite verbose, annoying, and error prone.
> errno = 0 > // code which may error here > if(errno) { … }
Which are the functions that set errno, and only errno, on failure?
In practice, you will clear errno once, and then repeatedly check for failure after every call to a libc function.
> And that errno is notably not scoped, so the code which may error should only be composed of calls to libc, or code whose interaction with libc you understand perfectly, otherwise you need to save and restore errno around uncontrolled calls.
I don't understand what this means.
It's a pain, and if it's not done correctly by everyone then it leaves you with subtle intermittent bugs.
libc included--the C11 threads API returns some errors directly using the constants thrd_busy, thrd_nomem, and thrd_timedout. Unfortunately, it also uses a catch-all constant, thrd_error, for other errors.
The pthreads API returns errno values directly as return values, but that's POSIX, not C.