fsync vs write system call

主宰稳场 提交于 2021-02-07 03:36:17

问题


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.

So what is the purpose of a system call like 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.


回答1:


Think of it as a layer of buffering.

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.

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.

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

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 :-)



来源:https://stackoverflow.com/questions/10371017/fsync-vs-write-system-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!