[Linux] 使用 fallocate 指令快速建立指定大小的檔案

[Linux] 使用 fallocate 指令快速建立指定大小的檔案

最近在測試一個專案上的問題,

需要將 Linux 上的磁碟空間灌爆,才比較容易重現這個問題,

但用 cp 來複製大檔案、或是用 dd 製造出大檔案都很慢,有沒有快一點的方式呢?

 

查了一下,原來有個叫做 fallocate 的指令,可以快速做出指定大小的檔案~

先來看一下求助訊息:

testuser@localhost ~ $ fallocate --help
Usage:
fallocate [options] <filename>
Options:
-n, --keep-size     don't modify the length of the file
-p, --punch-hole    punch holes in the file
-o, --offset <num>  offset of the allocation, in bytes
-l, --length <num>  length of the allocation, in bytes
-h, --help     display this help and exit
-V, --version  output version information and exit
For more details see fallocate(1).

 

舉例來說,使用 fallocate -l <size> 就能製造出指定大小的檔案,

我這邊前面再加上了 time 來測量一下時間,居然不用 0.1 秒就能做出來了,

而且檔案大小確實是我指定的數字:

testuser@localhost ~ $ time fallocate -l 4G bigfile
real    0m0.043s
user    0m0.001s
sys 0m0.039s
testuser@localhost ~ $ ll -h bigfile
-rw-r--r-- 1 root root 4.0G Dec  5 01:00 bigfile

 

要灌爆 Linux 磁碟的話,只要將大小設成很大的值就行了,

像我的磁碟空間剩不到 20GB,建立一個 20GB 的檔案會失敗,

但這就可以將磁碟灌爆了:

testuser@localhost ~ $ time fallocate -l 20G bigfile
fallocate: bigfile: fallocate failed: No space left on device
real    0m0.069s
user    0m0.002s
sys 0m0.067s
testuser@localhost ~ $ ll -h bigfile
-rw-r--r-- 1 root root 4.2G Dec  5 00:59 bigfile

 

參考資料:Quickly create a large file on a Linux system?

 

(本頁面已被瀏覽過 5,161 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料