问题
In Linux, how to ensure my system write() calls (and similar write-IO calls/variants) reach non-volatile storage, bypassing memory/cache/buffered-IO?
回答1:
See "Ensuring data reaches disk."
In short, the safest policy is O_DIRECT + fsync() at appropriate points.
回答2:
Using O_DIRECT would achieve the purpose but that can be inefficient for most applications, unless you are managing the whole file caching/buffering in your application. Typically there are two ways this is done.
- Use O_SYNC flag while opening the file, so that the writes will block till it is written to underlying persistent storage.
- Do the normal file operations and call fsync when you want to make sure the changes are written to storage device.
Remember if you are using mmap, then msync would be a better way to do the same.
来源:https://stackoverflow.com/questions/14385168/how-to-ensure-data-reaches-storage-bypassing-memory-cache-buffered-io