In errno.h
, this variable is declared as extern int errno;
so my question is, is it safe to check errno
value after some calls or use perror() in multi-threaded code. Is this a thread safe variable? If not, then whats the alternative ?
I am using linux with gcc on x86 architecture.
I think the answer is "it depends". Thread-safe C runtime libraries usually implement errno as a function call (macro expanding to a function) if you're building threaded code with the correct flags.
This is from
<sys/errno.h>
on my Mac:So
errno
is now a function__error()
. The function is implemented so as to be thread-safe.yes, as it is explained in the errno man page and the other replies, errno is a thread local variable.
However, there is a silly detail which could be easily forgotten. Programs should save and restore the errno on any signal handler executing a system call. This is because the signal will be handled by one of the process threads which could overwrite its value.
Therefore, the signal handlers should save and restore errno. Something like:
Yes, it is thread safe. On Linux, the global errno variable is thread-specific. POSIX requires that errno be threadsafe.
See http://www.unix.org/whitepapers/reentrant.html
Also see http://linux.die.net/man/3/errno
Yes
Errno isn't a simple variable anymore, it's something complex behind the scenes, specifically for it to be thread-safe.
See
$ man 3 errno
:We can double-check:
On many Unix systems, compiling with
-D_REENTRANT
ensures thaterrno
is thread-safe.For example: