Ubuntu 10.10 Pentax K-5

Tuesday, May 17, 2005

How to Avoid Corrupting Data. (write, fwrite in C)

1. Check the return status of open.
2. For the write(2), pwrite(2), writev(2), fwrite(3),,
* Don't submit writes larger than SSIZE_MAX
* Store the return code in a variable of type ssize_t
* If the return code is -1 and errno==EINTR, retry the call.
* If the return code is -1 inform the user and stop writing to the file
* If the return code is
Sample Code:

ssize_t ret;
size_t len;

if ( len > SSIZE_MAX ) {
/* This is a very bad idea */
}
again:
ret = write(fd, buf, len);
if ( ret < 0 ) {
if ( errno == EINTR )
goto again;
if ( errno == EAGAIN ) {
/* Wait with poll(2) for POLLOUT */
goto again;
}
/* A real error - signal the user */
}else if ( (size_t)ret < len ) {
buf += (size_t)ret;
len -= (size_t)ret;
goto again;
}
/* success */


3. Check the return status of close.
4. Synchonize the data. (fsync or fdatasync[fast])

Summary


1. Always check for errors whan using system calls that involve I/O.
2. Make sure if there is an unrecoverable error that the user knows about it right away, chances are they can do something to fix the problem. The worst possible thing to happen is that the user thinks that their data is safe and they don't find out until much later. Never indicate success unless you are absoultely certain.
3. Consider taking a performance hit and syncing data to the storage device before reporting success.
4. Don't remove or overwrite perfectly good data unless you know that what you are replacing it with is as safely written to disk as the old stuff.
5. Design the system in a way that the user can make usable backups easily and without interrupting service.

No comments: