3

When calling fsync() on a file, can the file become corrupted?

For example, say my file spreads across to disk blocks:

    A             B
|---------|    |--------|
| Hello,  | -> | World! |
|---------|    |--------|
| 1234567 |    | 89abcd |
|---------|    |--------|

Say I want to change the entire file contents to lower case (in a very inefficient manner). So I seek to position 1 of the file to change "H" into "h" and then position 8 to change "W" to "w". I then call fsync() on the file. The file is spread across two disk blocks.

  1. Is the ordering of the writes maintained?
  2. Is the fsync() operation atomic *across the disk
magnus
  • 4,031
  • 7
  • 26
  • 48

1 Answers1

1

The fsync call won't return until both writes are written to disk, along with any associated metadata. If your computer crashes (typically by losing power) and you have a corrupted file then log a bug report with the filesystem maintainers - that shouldn't happen. If fsync returns then the data is safely on disk.

To answer your questions though, there's no reason why the filesystem and disk driver can't reorder the writes (they see them as non-overlapping and it might be useful to write the second one first if that's where the disk head is on rotating media). And secondly there's no way for fsync to be atomic as it deals with real life hardware. It should act atomically though to the user (you will have the first copy of the file or the second but not something corrupted).

dave
  • 4,812
  • 4
  • 25
  • 38