fallocate vs dd 交换文件?

Ner*_*nux 27 swap dd

我想知道与创建交换文件有什么区别

fallocate -l 1G /swapfile
Run Code Online (Sandbox Code Playgroud)

dd if=/dev/zero of=/swapfile bs=1024 count=1024
Run Code Online (Sandbox Code Playgroud)

两者似乎都可以正常工作,但是一个比另一个有优势吗?

我在网上唯一能找到的是它fallocate不适用于所有文件系统。

mur*_*uru 31

mkswap手册页

Note  that  a  swap  file  must  not contain any holes.  Using cp(1) to
create the file is not acceptable.  Neither is use of  fallocate(1)  on
file  systems  that support preallocated files, such as XFS or ext4, or
on copy-on-write filesystems like btrfs.   It  is  recommended  to  use
dd(1)  and  /dev/zero in these cases.  Please read notes from swapon(8)
before adding a swap file to copy-on-write filesystems.
Run Code Online (Sandbox Code Playgroud)

而从swapon手册页

You should not use swapon on a file with holes.  This can  be  seen  in
the system log as

      swapon: swapfile has holes.

The  swap file implementation in the kernel expects to be able to write
to the file directly, without the assistance of the  filesystem.   This
is  a problem on preallocated files (e.g.  fallocate(1)) on filesystems
like XFS or ext4, and on copy-on-write filesystems like btrfs.
Run Code Online (Sandbox Code Playgroud)

因此,虽然fallocate可能比 快dd,但它不适合创建交换文件,并且不受交换相关工具的支持。

  • @stumblebee 并且在不支持预分配文件的文件系统上可以正常工作,其中 fallocate 基本上可以像 dd 一样工作,但不能在 ext4 上工作,ext4 是默认的,也是迄今为止最常用的 Linux 文件系统。 (5认同)
  • mkswap 手册页还说:要设置交换文件,必须在使用 mkswap 初始化该文件之前创建该文件,例如使用“fallocate --length 8GiB swapfile”之类的命令我很困惑。 (2认同)
  • 我有点困惑为什么“fallocate”会成为一个问题。看来,好吧,分配空间。(正如标签上所说。)并且在 `ext4` 上执行 `fallocate -l 1g /swaptest && mkswap /swaptest && swapon /swaptest` 不会抱怨任何事情。`truncate -l 1g` 会有所不同,因为它只设置文件大小但不分配任何块。 (2认同)

stu*_*bee 5

Fallocate 更快,来自Fallocate 联机帮助页

Fallocate用于操作为文件分配的磁盘空间,以取消分配或预分配它。 对于支持 fallocate系统调用的文件系统,通过分配块并将它们标记为未初始化来快速完成预分配,不需要对数据块进行IO。这比通过用零填充来创建文件要快得多。