技术解析

请教关于 dd 命令问题
0
2021-07-08 16:24:32
idczone

最近在用 dd 命令当作 16 进制编辑器来组装文件

用法类似于

dd status=none if=/dev/zero bs=1048576 count=${size} | tr '\000' '\377' > ${tmpfile}

先生成指定大小${size}的一个文件并用 0xFF 填充

分别写入几个小文件

dd status=none conv=notrunc if=${art} of=${tmpfile} seek=${artoffset} bs=1
dd status=none conv=notrunc if=${uboot} of=${tmpfile} seek=0 bs=1
dd status=none conv=notrunc if=${firmware} of=${tmpfile} seek=${ubootsize} bs=1

(估计有人看出来了,其实就是用来做编程器镜像的:P )

这个肯定是没问题的,但是在写入${firmware}的时候,会发现效率很低,因为 bs=1 嘛

于是我尝试修改了一下 bs ,结果带来 2 个问题

1 、因为一开始没意识到 seek 和 bs 的关系——按照 man 说明, seek 其实是 blocks ,也就是 seek * bs 才是最终 offset ,结果生成了一个超大的文件( 1.7TB ),这已经远远超出了我磁盘的空间,但是删除后没发现有什么文件被覆盖,为什么呢?是因为其实前面都被 seek 掉了么,其实写入的还是${firmware}流的大小?

2 、既然 seek 和 bs 紧密相关,有没有提高 I/O 效率的方式呢?


1.应该是 seek 超出大小又写入的话会自动 extend 文件
2.提高效率就不要用 dd ,写个 python 脚本绝对比这个简单

正常情况下 seek 不占用空间的。
$ truncate --size 15TiB a
$ dd if=/dev/null of=b seek=15 bs=1TiB count=0
$ ll
总用量 0
-rw-r--r-- 1 msg7086 msg7086 15T 10 月 11 16:47 a
-rw-r--r-- 1 msg7086 msg7086 15T 10 月 11 16:47 b

seek 并非和 bs 相关。
Let me google it for you: http://www.gnu.org/software/coreutils/manual/html_node/dd-invocation.html
‘ seek=n ’
Skip n ‘ obs ’-byte blocks in the output file before copying.
if ‘ oflag=seek_bytes ’ is specified, n is interpreted as a byte count rather than a block count.


1.应该是 seek 超出大小又写入的话会自动 extend 文件
请问是否有这样的资料可以参考?对您提到的这个 extend 机制。
2.提高效率就不要用 dd ,写个 python 脚本绝对比这个简单
因为一些原因无法安装 python ,所以仅限在 bash 下解决,目前我能想到的变通的方法是,单独生成填充块,然后用 cat 拼接,但是感觉这样做好 low 的。

谢谢!解释了我第一个问题的。


是的, Skip n ‘ obs ’-byte blocks in the output file before copying.
但是当定义 bs 的时候会覆盖 obs 和 ibs
不过您提到的
oflag=seek_bytes
是否对 dd 版本有要求?
dd (coreutils) 8.4
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Paul Rubin, David MacKenzie, and Stuart Kemp.
报错
dd: invalid output flag: `seek_bytes'

'\000' '\377'

2.tr '\000' '\377' 生成 0xFF 文件没有问题,现在是 MB 生成的
问题在于后面写入镜像碎片的时候


编译到
dd (coreutils) 8.24
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Paul Rubin, David MacKenzie, and Stuart Kemp.
可以使用 'seek_bytes' 参数,多谢!
问题已经解决。

这个东西叫做 file hole, 大部分文件系统都支持。主要用处是 sparse file, 比如 vm 镜像。可以看 man 2 lseek 还是 man 2 seek, 手机码字不去确认了

数据地带为您的网站提供全球顶级IDC资源
在线咨询
专属客服