One day, after many hard nights of debugging where a few bytes have gone missing in the middle of a stream, or your program has terminated with a write error when you have plenty of disk space left, or your user suspends your program with CTRL+Z you will look back on this with fond memories...
For write, it is common to just keep on trying the remaining buffer, until either all bytes are written, or a different error is received. Something like:
Code:
size_t written = 0;
while(length > 0) {
size_t bytes = write(df, buffer, length);
if(bytes == -1) {
if(errno == EINTR)
continue;
return -1; // Or however you want to handle error
} else {
buffer += bytes;
length -= bytes;
written += bytes;
}
}
return written;
Here's part of the "safe-read.c", that is part of GNU coreutils, which just checks for EINTR:
Code:
size_t
safe_rw (int fd, void const *buf, size_t count)
{
for (;;)
{
ssize_t result = rw (fd, buf, count);
if (0 <= result)
return result;
else if (IS_EINTR (errno))
continue;
else if (errno == EINVAL && SYS_BUFSIZE_MAX < count)
count = SYS_BUFSIZE_MAX;
else
return result;
}
}