Writing and reading the same fd without fsync in Linux
Asked Answered
L

3

7

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.

Luciana answered 17/12, 2011 at 18:43 Comment(0)
A
10

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.

Abaca answered 17/12, 2011 at 18:46 Comment(4)
Thanks. Is there any specific reason to use 2 descriptors?Luciana
Because it makes the job easier? ;)Abaca
What with writing to one fd and reading in another fd? What if I write something in one fd without flushing, without closing a file and then I read in second file descriptor? Will I get in second file descriptor what I wrote in first without doing flush?Italia
Yes, it is guaranteed by the operating system. Is there any source (e.g. URL or source code) for it?Supererogatory
V
3

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

Valina answered 17/12, 2011 at 18:45 Comment(0)
L
1

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().

Lackaday answered 17/12, 2011 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.