Is there a cleaner way to use the write() function reliably?

c, gcc, linux, sockets

Solution

You have a bit of a "don't repeat yourself" problem there - there's no need for two separate calls to `write`, nor for two nested loops.

My normal loop would look something like this:

for (int n = 0; n < count; ) {
    int ret = write(fd, (char *)buf + n, count - n);
    if (ret < 0) {
         if (errno == EINTR || errno == EAGAIN) continue; // try again
         perror("write");
         break;
    } else {
        n += ret;
    }
}

// if (n < count) here some error occurred

Problem

I read the `man` pages, and my understanding is that if `write()` fails and sets the `errno` to `EAGAIN` or `EINTR`, I may perform the `write()` again, so I came up with the following code: ``` ret = 0; while(ret != count) { write_count = write(connFD, (char *)buf + ret, count); while (write_count < 0) { switch(errno) { case EINTR: case EAGAIN: write_count = write(connFD, (char *)buf + ret, count -ret); break; default: printf("\n The value of ret is : %d\n", ret); printf("\n The error number is : %d\n", errno); ASSERT(0); } } ret += write_count; } ``` I am performing `read()` and `write()` on sockets and handling the `read()` similarly as above. I am using Linux, with `gcc` compiler.

Original source