Nuno V.
Nuno V.

Reputation: 83

Defining errno values for library functions

I'm writing a small library to handle comunications with an rs232 device.

Most of the functions write a few bytes in the descriptor, wait for the reply, analise it and return:

int demo_function(int fd)
{
    if (sendcommand(command)==0)
    {
        if (getreply(buffer)==0)
        {
            if (buffer == ACK)
                return 0;           //Success, returns 0
            else if (buffer == NACK)
                return -1;          //Error, Nack received
            else
                return -1;          //Error, unexpected answer
        }
        else
            return -1;              //Error, Timeout
    }
    else
        return -1;                  //Error, send failled.
}

I wanted to follow the standard as much as possible, so i'm returning 0 on success, -1 on error. I need to define the values i should set in errno.

-Nack received: I couldn't find any error that suited this case.

-Unexpected answer: EBADMSG.

-Timeout: ETIME or ETIMEDOUT.

-Send failled: EIO ?

What error should i use for the NACK case, and are the error numbers in the other cases suitable? Or should i stay the hell out of errno and find another way for reporting the errors (like diferent return values)?

Upvotes: 1

Views: 276

Answers (2)

cnicutar
cnicutar

Reputation: 182744

Look at the standard for a list of errnos. Personally I would stay away from errno, and use separate parameters etc.

In your case the function doesn't return anything useful so you could use the return value as an indication of success (0) or the type of error (!0).

Upvotes: 1

thiton
thiton

Reputation: 36059

You should probably distinguish in return value between expected device answers (like ACK and NACK) and general, unexpected system failures (like timeouts, failed sends, etc.). I'd recommend returning 0 on success, 1 on NACK and -1+errno on system failures.

Upvotes: 1

Related Questions