Linux?-?errno是不是线程安全的

来源:百度文库 编辑:神马文学网 时间:2024/10/04 16:04:43

    观点一:

    errno是个全局变量,应该不是线程安全的吧.

    观点二

    可以的。
    extern int*__errno_location(void)
    #define errno (*__errno_location())
    保证自己维护一个;

    观点三:

    没问题,线程之间不影响,实际errno是一个函数;

    观点四:

    线程对信号的反应,会随系统不同而有些差异,并不是全部按照posix标准(记得早期的posix标准在这一点上似乎也比较模糊),在redhat linux7.2上,发送给进程的信号,会被发送给进程内所有的线程,而在solaris和redhat9上,只有主线程才接受到发给进程的信号另外,要当心在多线程应用中error变量只有在定义了宏_REENTRANT后,才会有如下的定义出现:
    int * __errno_location();
    #define errno (*__errno_location())
否则,errno只是一个非线程安全的全局变量,因此perror也将没有准确的含义。     我自己在虚拟机上安装的Fedora 5中用man errno得到如下内容,请大家认真阅读:    The <errno.h> header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate  what  went wrong. Its value is significant only when the call returned an error (usually -1), and a function that does  succeed is allowed to change errno. Sometimes,  when  -1 is also a valid successful return value one has to zero errno before the call in order to detect possible errors.    errno is defined by the ISO C standard to be  modifiable  lvalue of type int,  and  must not be explicitly declared; errno may be a macro. errno is thread-local; setting it in one thread does not affect its value in any other thread.    Valid error numbers are all non-zero; errno is never set to zero by any library function.  All the error names specified by POSIX.1  must  have distinct  values,  with  the exception of EAGAIN and EWOULDBLOCK, which may be the same.       至于什么是thread_local,下面给出一段Windows上TLS的定义供参考学习:       Thread local storage (TLS) is the method by which each thread in a multithreaded process allocates a location in which to store thread-specific data.       我的理解就是每个线程都有一个自己的errno,互相之间不影响。其实等于没有说,setting it in one thread does not affect its value in any other thread 已经说的够清楚了。呵呵!