fallocate和dd哪个更适合用于创建swap文件?

我想知道使用哪种方法创建交换文件的区别是什么。

fallocate -l 1G /swapfile

dd if=/dev/zero of=/swapfile bs=1024 count=1024

两者似乎都能正常工作,但是有没有一个比另一个更有优势呢?
我在网上找到的唯一信息是,fallocate 在所有文件系统上都不起作用。

1fallocate通常更快(因为它不会用零填充创建的文件)-否则没有区别,最终结果是相同的。请参见:https://antipaucity.com/2017/08/31/fallocate-vs-dd-for-swap-file-creation/ - Jonas Czech
2@JonasCz:是的...但也不完全!请看muru的回答。 - David Foerster
2个回答

the mkswap manpage中:

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.

the swapon manpage中可以得到以下信息:
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.

尽管可能比
更快,但它不适用于创建交换文件,并且不受与交换相关的工具支持。

1mkswap的手册还说:要设置交换文件,必须在使用mkswap初始化之前创建该文件,例如使用类似fallocate --length 8GiB swapfile的命令。我感到困惑。 - stumblebee
8@stumblebee 在不支持预分配文件的文件系统上,这将很好地运行,其中fallocate基本上可以像dd一样工作,但在ext4上不行,它是默认和迄今为止最常用的Linux文件系统。 - muru
2我有点困惑为什么fallocate会成为一个问题。它似乎在分配空间。(就像标签上说的那样。)而且,在ext4上执行fallocate -l 1g /swaptest && mkswap /swaptest && swapon /swaptest没有任何错误提示。而truncate -l 1g则不同,因为它只是设置文件的大小,而没有分配任何块。 - ilkkachu
fallocate(1)的手册中:对于支持fallocate系统调用的文件系统,预分配是通过分配块并将其标记为未初始化来快速完成的... - Will Crawford
1所以如果它没有做到这一点,就需要有人提交一个错误报告 :) - Will Crawford
1@ilkkachu 有人在xfs上复现了这个问题,至少在这个链接中:https://bugzilla.redhat.com/show_bug.cgi?id=1129205 - muru
有趣。我在ext4和xfs系统上使用fallocate从未遇到过问题。(当然,这并不经常发生...) - RonJohn
手册已经改变了。我不确定如何阅读它,但我认为在Linux版本大于等于4.18时,可以使用fallocate命令来为xfs文件系统分配空间。http://manpages.ubuntu.com/manpages/eoan/zh_CN/man8/swapon.8.html - lumbric

Fallocate更快,来自the fallocate manpage

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