1

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

Nuno V.
  • 73
  • 7

2 Answers2

1

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.

thiton
  • 35,651
  • 4
  • 70
  • 100
1

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

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Would you use negative or positive integers for the errors? I'm still trying to make my mind, as a few errors can be reported with further detail (write and read faillures, inside the sendcommand and getreply functions). On other hand, i probably can't cover all the faillure cases, so maybe i should stay out of it. – Nuno V. Oct 27 '11 at 10:54