dd v.s. fallocate v.s. truncate

因為在 centos 7 上面要做 swapfile, 結果用 fallocate 出來的不能用,所以順便查一下

主要摘錄自這篇 http://ram.kossboss.com/dd-fallocate-truncate-making-big-files-quick/


# use dd to create 10 g file
$ dd if=/dev/zero of=10gigfile bs=1M count=10240
# use fallocate to create 10 g file
$ fallocate -l 10G 10gig
# use fallocate to append 10 g space to the file
$ fallocate -o 10G -l 10G 10gig
# use truncate to create 10 g file
$ truncate -s 10G tengig
# use truncate to append 10 g to the file
$ truncate -s +10G tengig

簡單來說,dd是 allocate 了 disk space,且寫入 0。
truncate等於是宣稱自己有 allocate 空間,但實際上沒有。
fallocate會跟磁碟真的要了空間(sparse file),但是沒有寫入任何資料。
但對於要做 swapfile 使用的話,用 dd 的方式比較好,主要原因是 centos 7 用 XFS,結果要到的空間會是”files without holes

dd is the obvious first choice, but dd is essentially a copy and that forces you to write every block of data (thus, initializing the file contents)… And that initialization is what takes up so much I/O time. (Want to make it take even longer? Use /dev/random instead of /dev/zero! Then you’ll use CPU as well as I/O time!) In the end though, dd is a poor choice (though essentially the default used by the VM “create” GUIs).

truncate is another choice — and is likely the fastest… But that is because it creates a “sparse file”. Essentially, a sparse file is a section of disk that has a lot of the same data, and the underlying filesystem “cheats” by not really storing all of the data, but just “pretending” that it’s all there. Thus, when you use truncate to create a 20 GB drive for your VM, the filesystem doesn’t actually allocate 20 GB, but it cheats and says that there are 20 GB of zeros there, even though as little as one track on the disk may actually (really) be in use.

fallocate is the final — and best — choice for use with VM disk allocation, because it essentially “reserves” (or “allocates” all of the space you’re seeking, but it doesn’t bother to write anything. So, when you use fallocate to create a 20 GB virtual drive space, you really do get a 20 GB file (not a “sparse file”, and you won’t have bothered to write anything to it — which means virtually anything could be in there — kind of like a brand new disk!)