# Read function that properly handles interrupts

This function is meant to be used for reading files. It returns all bytes asked unless EOF is reached. It handles interrupts and returns -1 on errors.

//safe function to read all bytes asked, only returns less bytes if EOF
static ssize_t read_all(int fdes, void *buffer, size_t size)
{
ssize_t ret;
ssize_t ret2;

if(ret == -1){
if(errno == EINTR)

return -1;
}

if(ret && ret != size){
ret2 = read_all(fdes, buffer + ret, size - ret);
if(ret2 == -1)
return -1;

return ret + ret2;
}

return ret;
}

• It is recommended to state what specifically you want to get reviewed in your question. – ChrisWue Jan 19 '16 at 2:31

My main problem is the recursion. I don't think its major but I personally would use a loop. Given the current layout I can't quite convince myself that it works in all situations (especially since there are two alternative recursive calls).

Declare variables close to the usage point (rather than everything at the top).

    ssize_t ret;
ssize_t ret2;


C has been updated so that you can declare variables at any point in a function. This helps in readability as you don't need to scroll far to find the variable declaration. Also if you declare in the most restrictive scope possible it helps to prevent data leaking (out of a scope).

Try this:

static ssize_t read_all(int fdes, void* buffer, ssize_t size)
{

{

if ((thisRead == -1) && (errno == EINTR)) {
continue;
}
// Note: There are other errors that may not be erros.
// EAGAIN or EWOULDBLOCK spring to mind but may need special handling
// as immediately calling read may just cause a busy wait you may
// want to suspend the thread by calling sleep..