在 errno.h
中,这个变量被声明为 extern int errno;
所以我的问题是,检查 errno
值是否安全经过一些调用或在多线程代码中使用 perror() 。这是一个线程安全变量吗?如果没有,那还有什么替代方案?
我在 x86 架构上使用带有 gcc 的 linux。
最佳答案
是的,它是线程安全的。在 Linux 上,全局 errno 变量是线程特定的。 POSIX 要求 errno 是线程安全的。
见 http://www.unix.org/whitepapers/reentrant.html
In POSIX.1, errno is defined as an external global variable. But this definition is unacceptable in a multithreaded environment, because its use can result in nondeterministic results. The problem is that two or more threads can encounter errors, all causing the same errno to be set. Under these circumstances, a thread might end up checking errno after it has already been updated by another thread.
To circumvent the resulting nondeterminism, POSIX.1c redefines errno as a service that can access the per-thread error number as follows (ISO/IEC 9945:1-1996, §2.4):
Some functions may provide the error number in a variable accessed through the symbol errno. The symbol errno is defined by including the header , as specified by the C Standard ... For each thread of a process, the value of errno shall not be affected by function calls or assignments to errno by other threads.
另见 http://linux.die.net/man/3/errno
errno is thread-local; setting it in one thread does not affect its value in any other thread.
关于c - errno 是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1694164/