理解 C 中的 errno

Understanding errno in C

如果我想使用一个可能 return 错误的函数,例如 thread_mutexattr_init(&myAttr),如果此函数 return 是一个错误,它将自动设置 errno 为错误的编号还是应该将 errno 设置为此函数的 return?

例如什么是正确的做法?

if((errno = pthread_mutexattr_init(&myAttr)) != 0){
    if(errno == EBUSY){
        perror("some error message because of EBUSY");
    }else{
        perror("another error message");
}

或者这样:

if(pthread_mutexattr_init(&myAttr) < 0){
    if(errno == EBUSY){
        perror("some error message because of EBUSY");
    }else{
        perror("another error message");
    }  
}

第一个版本是正确的(第二个实际上是错误的 - pthread_mutexattr_init() 需要 return 成功时为零或失败时为正错误数;未定义设置errno 所以 errno 中的值不一定相关)。

POSIX 不要求 pthreads 函数设置 errno(它们可能设置也可能不设置——没有要求)。 returned 值本身就是错误号。如果 returned 值是 0 那么成功,如果它是其他任何东西,你可以将它分配给 errno 来查找错误(或使用任何其他 int 变量来保存值,然后将其传递给 strerror(),例如)。