Daniel Oliveira Daniel Oliveira - 1 month ago 5
C Question

Understanding errno in C

If I want to use a function that may return an error, for example thread_mutexattr_init(&myAttr), if this function returns an error it will automatically set errno with the number of the error or should I set errno to the return of this function?

For example what is right to do?

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


Or this:

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

usr usr
Answer

The first version is correct out the two (the second is wrong actually - pthread_mutexattr_init() is required to return zero on success or a positive error number on failure; it is not required (permitted?) to set errno).

POSIX does not mandate pthreads functions to set errno (they may or may not set it -- there's no requirement). The returned value itself is the error number. If the returned value is 0 then success and if it's anything else you can assign it to errno to find the error (or use any other int variable to hold the value and then pass that to strerror(), for example).