为什么dd有时不等到数据写入?

jgi*_*ich 20 linux command-line dd

有时,当我将图像写入闪存驱动器时,会发生这种情况:

$ sudo dd if=install57.fs of=/dev/sdc
573440+0 records in
573440+0 records out
293601280 bytes (294 MB) copied, 0.549231 s, 535 MB/s
Run Code Online (Sandbox Code Playgroud)

基本上,Linux 缓存所有内容,不写入任何内容,然后dd退出。键入 后sync,它开始写入数据(闪存驱动器 LED 开始闪烁)。

为什么会发生这种情况?

cha*_*aos 21

改用这个:

sudo dd if=install57.fs of=/dev/sdc conv=fsync
Run Code Online (Sandbox Code Playgroud)

fsync()在每个write()系统调用之后调用。这会强制dd不缓存任何内容。请参阅 fsync ( man 2 fsync)联机帮助页的这一部分:

fsync() transfers ("flushes") all modified in-core data of (i.e., modified buffer cache 
pages for) the file referred to by the file descriptor fd to the disk device (or other 
permanent storage device) where that file resides. The call blocks until the device reports 
that the transfer has completed. It also flushes metadata information associated with the 
file (see stat(2)).
Run Code Online (Sandbox Code Playgroud)

这是内核的默认行为。Linux 内核像这样管理写入和读取缓存:当write()发出系统调用时,数据会快速写入缓存并向进程发送写入完成状态。当需要缓冲区或总线上有空闲时间时,将数据从缓存写入硬盘。


Chr*_*ton 10

发生这种情况是因为 Linux 和大多数其他操作系统都缓存读取和写入。在大多数情况下,这会使您的操作系统响应更快。

sync如您所知,如果您想确保已写入缓存数据,您需要使用。Linux 公开了大量您可以调整的设置。本文很好地概述了一些设置。例如,您可以将 vm.dirty_background_bytes 设置为 0,以确保内核立即启动刷新线程。


Ste*_*ven 7

sync(8) - Linux 手册页

内核将数据保存在内存中以避免进行(相对较慢的)磁盘读写。这提高了性能,但如果计算机崩溃,数据可能会丢失或文件系统因此损坏。同步确保内存中的所有内容都写入磁盘。

注意:(unmount或弹出)自动调用syncwhich 在正常文件系统使用中“隐藏”了它。