1

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"); } } 

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Although the POSIX standard does not say that the pthread functions are prohibited from setting errno, the definition of errno says: The value of errno shall be defined only after a call to a function for which it is explicitly stated to be set… and <errno.h> says: The <errno.h> header shall define the following macros which shall expand to integer constant expressions with type int, distinct positive values (except as noted below)…
Since pthread_mutexattr_init() is not defined to set errno, it is not admissible (sensible) to check errno after the call. And the function never returns a negative number: it returns 0 on success and a positive integer on failure.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.