Reputation: 1290
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");
}
}
Upvotes: 1
Views: 637
Reputation: 121427
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 defined to set errno
so the value in errno
is not necessarily relevant).
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).
Upvotes: 4