根本不理解dd命令参数

Sea*_*ean 12 bash dd

我对dd命令很熟悉,但我很少需要自己使用它.今天我需要,但我遇到的行为似乎很奇怪.

我想创建一个100M的文本文件,每行包含单个单词"testing".这是我的第一次尝试:

~$ perl -e 'print "testing\n" while 1' | dd of=X bs=1M count=100
0+100 records in
0+100 records out
561152 bytes (561 kB) copied, 0.00416429 s, 135 MB/s
Run Code Online (Sandbox Code Playgroud)

嗯,这很奇怪.其他组合怎么样?

~$ perl -e 'print "testing\n" while 1' | dd of=X bs=100K count=1K
0+1024 records in
0+1024 records out
4268032 bytes (4.3 MB) copied, 0.0353145 s, 121 MB/s

~$ perl -e 'print "testing\n" while 1' | dd of=X bs=10K count=10K
86+10154 records in
86+10154 records out
42524672 bytes (43 MB) copied, 0.35403 s, 120 MB/s

~$ perl -e 'print "testing\n" while 1' | dd of=X bs=1K count=100K
102400+0 records in
102400+0 records out
104857600 bytes (105 MB) copied, 0.879549 s, 119 MB/s
Run Code Online (Sandbox Code Playgroud)

因此,在这四个明显等效的命令中,所有产生不同大小的文件,其中只有一个是我期望的文件.这是为什么?

编辑:通过,我有点尴尬,我没有想到"是测试",而不是那个更长的Perl命令.

ste*_*fan 7

我还不确定为什么,但在保存之前使用此方法不会填满整个块.尝试:

perl -e 'print "testing\n" while 1' | dd of=output.txt bs=10K count=10K iflag=fullblock
10240+0 records in
10240+0 records out
104857600 bytes (105 MB) copied, 2.79572 s, 37.5 MB/s
Run Code Online (Sandbox Code Playgroud)

iflag=fullblock似乎迫使DD累积输入,直到块满了,虽然我不知道为什么这是不是默认的,或者它实际上在默认情况下做什么.


Gil*_*il' 7

要查看正在发生的事情,让我们看一下strace类似调用的输出:

execve("/bin/dd", ["dd", "of=X", "bs=1M", "count=2"], [/* 72 vars */]) = 0
…
read(0, "testing\ntesting\ntesting\ntesting\n"..., 1048576) = 69632
write(1, "testing\ntesting\ntesting\ntesting\n"..., 69632) = 69632
read(0, "testing\ntesting\ntesting\ntesting\n"..., 1048576) = 8192
write(1, "testing\ntesting\ntesting\ntesting\n"..., 8192) = 8192
close(0)                                = 0
close(1)                                = 0
write(2, "0+2 records in\n0+2 records out\n", 31) = 31
write(2, "77824 bytes (78 kB) copied", 26) = 26
write(2, ", 0.000505796 s, 154 MB/s\n", 26) = 26
…
Run Code Online (Sandbox Code Playgroud)

会发生什么事情,dd只需一次read()调用即可读取每个块.从磁带读取时这是合适的,这是dd最初主要用于的磁带.在磁带上,read真的读取一个块.从文件中读取时,必须注意不要指定过大的块大小,否则read将被截断.从管道读取时,情况更糟:您读取的块的大小取决于生成数据的命令的速度.

这个故事的寓意不是用来dd复制数据,除了安全的小块.从来没有从管道除外bs=1.

(GNU dd有一个fullblock标志来告诉它表现得体面.但其他实现却没有.)