What is the best command for creating a swap file on Linux?
This tutorial explains which is the best command for creating a swap file on Linux.
`Fallocate` VS `dd` Commands in Linux
fallocate
is much much faster, it may create files with holes. It simply means the space is not contiguous, which is bad for swap files. So fallocate
creates a C-style linked-list of memory, whereas dd
creates a C-array contiguous block of memory. Swap files need a contiguous block. dd
does this by doing a byte-for-byte copy of binary zeros from the /dev/zero
pseudo-file into a new file it generates.
swapon manpage also states not to use fallocate
, and to use dd
instead.
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.
mkswap manpage also states not to use fallocate
, and to use dd
instead.
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.