fsync vs写系统调用 [英] fsync vs write system call

查看:54
本文介绍了fsync vs写系统调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一个基本的问题,即使用fsync之类的系统调用何时有用.我是初学者,总是给人一种印象,就是写足以写一个文件,而使用write的示例实际上是写到文件的最后.

I would like to ask a fundamental question about when is it useful to use a system call like fsync. I am beginner and i was always under the impression that write is enough to write to a file, and samples that use write actually write to the file at the end.

那么像fsync这样的系统调用的目的是什么?

So what is the purpose of a system call like fsync?

仅提供一些背景知识,我使用的是Berkeley DB库5.1.19版,因此有很多关于fsync()与仅编写成本的讨论.这就是我想知道的原因.

Just to provide some background i am using Berkeley DB library version 5.1.19 and there is a lot of talk around the cost of fsync() vs just writing. That is the reason i am wondering.

推荐答案

将其视为缓冲层.

如果您熟悉 fopen fprintf 之类的标准C调用,您应该已经意识到C运行时库自身中正在发生缓冲.

If you're familiar with the standard C calls like fopen and fprintf, you should already be aware of buffering happening within the C runtime library itself.

刷新这些缓冲区的方法是使用 fflush 来确保将信息从C运行时库传递到OS(或周围环境).

The way to flush those buffers is with fflush which ensures that the information is handed from the C runtime library to the OS (or surrounding environment).

但是,仅因为操作系统具有它,并不意味着它就在磁盘上.它也可以在操作系统中缓冲.

However, just because the OS has it, doesn't mean it's on the disk. It could get buffered within the OS as well.

这是 fsync 所要处理的,确保将OS缓冲区中的内容物理写入磁盘.

That's what fsync takes care of, ensuring that the stuff in the OS buffers is written physically to the disk.

您通常会在日志库中看到这种操作:

You may typically see this sort of operation in logging libraries:

fprintf (myFileHandle, "something\n");  // output it
fflush (myFileHandle);                  // flush to OS
fsync (fileno (myFileHandle));          // flush to disk

fileno 是一项功能,可为您提供给定 FILE * 文件句柄和 fsync <描述符上的/code>进行最终的刷新.

fileno is a function which gives you the underlying int file descriptor for a given FILE* file handle, and fsync on the descriptor does the final level of flushing.

现在 是一项相对昂贵的操作,因为磁盘写操作通常比内存中的传输要慢得多.

Now that is a relatively expensive operation since the disk write is usually considerably slower than in-memory transfers.

与日志记录库一样,另一用例可能对这种行为很有用.让我看看我是否还记得那是什么.对,就是那样.数据库!就像Berzerkely DB一样.您想要确保数据在磁盘上的位置,这是满足ACID要求的相当有用的功能:-)

As well as logging libraries, one other use case may be useful for this behaviour. Let me see if I can remember what it was. Yes, that's it. Databases! Just like Berzerkely DB. Where you want to ensure the data is on the disk, a rather useful feature for meeting ACID requirements :-)

这篇关于fsync vs写系统调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆