문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top