Question

Suppose I write a block to a file descriptor without doing fsync and then read the same block from the same descriptor some time later. Is it guaranteed that I will receive the same information?

The program is single-threaded and no other process will access the file at any time.

Was it helpful?

Solution

Yes, it is guaranteed by the operating system.

Even if the modifications have not made it to disk yet, the OS uses its buffer cache to reflect file modifications and guarantees atomicity level for reads and writes, to ALL processes. So not only your process, but any other process, would be able to see the changes.

As to fsync(), it only instructs the operating system to do its best to flush the contents to disk. See also fdatasync().

Also, I suggest you use two file descriptors: one for reading, another for writing.

OTHER TIPS

fsync() synchronizes cache and disk. Since the data is already in the cache, it will be read from there instead of from disk.

When you write to a file descriptor, the data is stored in ram caches and buffers before being sent to disk. So as long as you don't close the descriptor, you can access the data you just wrote. If you close the descriptor, the file contents must be put to disk either by flushing it yourself or waiting for the OS to do it for efficiency, BUT if you want to be assured to access the just written data on disk after opening a new FD, you MUST flush to disk with fsync().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top