2015年5月19日 星期二

linux sync指令


Linux 系統中,為了加快資料的讀取速度,寫入硬盤的資料有的時候為了效能,會寫到 filesystem buffer 中,這個 buffer 是一塊記憶體空間,如果欲寫入硬碟的資料存此 buffer 中,而系統又突然斷電的話,那資料就會流失!


  • 可以透sync 指令,將存 buffer 中的資料強制寫入disk中;


Name

sync - synchronize data on disk with memory

Synopsis

sync [--help] [--version]

Description

 sync writes any data buffered in memory out to disk. This can include (but is not limited to) modified superblocks, modified inodes, and delayed reads and writes. This must be implemented by the kernel; The sync program does nothing but exercise the sync system call.
The kernel keeps data in memory to avoid doing (relatively slow) disk reads and writes. This improves performance, but if the computer crashes, data may be lost or the file system corrupted as a result. sync ensures that everything in memory is written to disk.

sync should be called before the processor is halted in an unusual manner (e.g., before causing a kernel panic when debugging new kernel code). In general, the processor should be halted using the shutdown or reboot or halt commands, which will attempt to put the system in a quiescent state before calling sync.




  • 或是在程式中利用sync() function ;


Name

sync - commit buffer cache to disk

Synopsis

#include <unistd.h>

void sync(void);

Feature Test Macro Requirements for glibc

sync():
_BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED


Description

sync() causes all buffered modifications to file metadata and data to be written to the underlying file systems.

Errors

sync() is always successful.


資料來源:
sync(2) - Linux man page
sync(8) - Linux man page