在Linux中不使用fsync写入和读取相同的fd
假设我在不执行 fsync 的情况下将一个块写入文件描述符,然后在一段时间后从同一描述符读取同一块。是否保证我会收到相同的信息?
该程序是单线程的,任何时候都不会有其他进程访问该文件。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是由操作系统保证的。
即使修改尚未写入磁盘,操作系统也会使用其缓冲区缓存来反映文件修改并保证所有进程的读取和写入的原子性级别。因此,不仅您的进程,而且任何其他进程都能够看到更改。
至于
fsync()
,它只是指示操作系统尽力将内容刷新到磁盘。另请参阅fdatasync()
。另外,我建议您使用两个文件描述符:一个用于读取,另一个用于写入。
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 alsofdatasync()
.Also, I suggest you use two file descriptors: one for reading, another for writing.
fsync()
同步缓存和磁盘。由于数据已经在缓存中,因此将从缓存中读取数据,而不是从磁盘中读取。fsync()
synchronizes cache and disk. Since the data is already in the cache, it will be read from there instead of from disk.当您写入文件描述符时,数据在发送到磁盘之前会存储在 RAM 缓存和缓冲区中。所以只要不关闭描述符,就可以访问刚刚写入的数据。如果关闭描述符,则必须通过自己刷新或等待操作系统将文件内容写入磁盘以提高效率,但是如果您想在打开新的 FD 后确保访问磁盘上刚刚写入的数据,您必须使用
fsync()
刷新到磁盘。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()
.