LinuxCommandLibrary

fadvise

Advise the kernel about file access patterns

TLDR

Preload a file or directory into cache

$ fadvise [[-a|--advice]] willneeded [path/to/file_or_directory]
copy

Suggest dropping a file from cache
$ fadvise [path/to/file]
copy

Display help
$ fadvise [[-h|--help]]
copy

SYNOPSIS

#include <fcntl.h>

int posix_fadvise(int fd, off_t offset, off_t len, int advice);

PARAMETERS

fd
    File descriptor referring to the file.

offset
    Start offset (in bytes) of the advised region.

len
    Length (in bytes) of the region; 0 means from offset to EOF.

advice
    Hint value: POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL, etc.

DESCRIPTION

posix_fadvise is a system call (not a standalone shell command) that allows applications to provide the kernel with hints about expected I/O access patterns for a specific region of a file. This enables optimizations like improved page caching, prefetching data into memory, or evicting pages early to free resources.

It takes a file descriptor, a byte range (offset and length), and an advice hint. The kernel may act on these hints to enhance performance, though it is not obligated to do so—hints are advisory only.

Key benefits include better handling of sequential reads (e.g., streaming media), random access (e.g., databases), or regions unlikely to be reused (e.g., temporary files). For example, hinting sequential access might trigger aggressive readahead; hinting "don't need" might drop pages from cache.

This is particularly useful in high-performance I/O applications like databases, multimedia processing, or backup tools. It complements madvise for memory mappings. Note: implemented in libc, invoked from C/C++ programs via <fcntl.h>. No direct shell equivalent exists, but tools like fio or custom scripts can invoke it via ioctl or libraries.

CAVEATS

Hints are non-binding; kernel/filesystem may ignore. Invalid args return EINVAL. Non-seekable files (pipes) return ESPIPE. No effect on non-regular files sometimes. Off_t size depends on _FILE_OFFSET_BITS.

ADVICE HINTS

POSIX_FADV_NORMAL: Normal access (default readahead).
POSIX_FADV_SEQUENTIAL: Read sequentially forward.
POSIX_FADV_RANDOM: Random page access.
POSIX_FADV_NOREUSE: Access once, won't reuse.
POSIX_FADV_WILLNEED: Will access soon (prefetch).
POSIX_FADV_DONTNEED: Won't access soon (drop cache).

RETURN VALUES

0 on success; -1 and sets errno on error (e.g., EBADF, EINVAL).

HISTORY

Introduced in Linux 2.4 (2001). Standardized in POSIX.1-2003. fadvise64_64(2) added for explicit 64-bit offsets. Widely supported in modern kernels; glibc wrapper since 2.2.

SEE ALSO

madvise(2), posix_madvise(3), readahead(2), fadvise64_64(2)

Copied to clipboard