如果我想使用一个可能返回错误的函数,例如 thread_mutexattr_init(&myAttr),如果这个函数返回一个错误,它会自动将错误编号设置为 errno,或者我应该将 errno 设置为这个函数的返回值功能?
例如什么是正确的做法?
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()
需要在成功时返回零或在失败时返回正错误号;它没有定义设置 errno
所以 errno
中的值不一定相关)。
POSIX 不要求 pthreads 函数设置 errno
(它们可能设置也可能不设置——没有要求)。返回值本身就是错误号。如果返回值为 0
则成功,如果是其他任何值,您可以将其分配给 errno
以查找错误(或使用任何其他 int
变量来保存值,然后将其传递给 strerror()
,例如)。
关于c - 理解 C 中的 errno,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40455521/