Should I set errno?

I'm writing a module which exports an interface similar to send and recv.

Since those functions are supposed to return respectively the number of sent and received bytes, I cannot do proper error management as I would do normally (i.e. using enumeratives and returning mnemonic values).

In a situation like this should I set errno as the standard library does? If so, since errno is thread specific, is there a particular way of writing on it, or can I simply assign a value to it?

Edit: experimenting it I noticed that setting errno by assignment is working. Still: is this safe and portable for any system?


Solution 1:

This is a bit old, but errno - manual section 3 says that you can directly assign to it, even though it is a macro, and it will be thread local

Solution 2:

Not only can you set errno, in many cases you should set errno. When calling some library functions you can only reliably detect an error if you first set errno to zero. See strtol for an example.

From the POSIX specification of strtol:

[CX] [Option Start] The strtol() function shall not change the setting of errno if successful.

Since 0, {LONG_MIN} or {LLONG_MIN}, and {LONG_MAX} or {LLONG_MAX} are returned on error and are also valid returns on success, an application wishing to check for error situations should set errno to 0, then call strtol() or strtoll(), then check errno. [Option End]