posix_fadvise(2)
Declare the expected access pattern for a file region so the kernel can tune readahead and page-cache reclaim.
- Since
- Linux 2.5.60check your kernel →
- glibc
- glibc 2.2
- System
- Linux
- Man page
- posix_fadvise(2)
Synopsis
#include <fcntl.h>
int posix_fadvise(int fd, off_t offset, off_t len, int advice);Rod's take
FADV_WILLNEED fires a background readahead before you open the hot path — same idea as readahead(2) but expressed per-range. FADV_DONTNEED is the useful one for sequential workloads: after you finish streaming a large file, DONTNEED evicts those pages so you stop polluting the LRU with data you will never touch again. The kernel does not guarantee any of this — it is advisory, not a contract — but on Linux the DONTNEED path actually does free clean pages immediately, which is why backup and log-rotation tools call it after each chunk.
Flags and arguments that matter
Browse flag index →| Name | What it does |
|---|---|
| POSIX_FADV_NORMAL | Reset to the default read-ahead policy. Cancels any earlier FADV hint on the range. |
| POSIX_FADV_SEQUENTIAL | Data will be read start-to-end. Kernel doubles its read-ahead window on the range. |
| POSIX_FADV_RANDOM | Access will be random. Kernel disables read-ahead; pages are fetched on demand only. |
| POSIX_FADV_WILLNEED | Initiate read-ahead for the range now so pages are warm by the time the application reads them. Asynchronous and non-blocking. |
| POSIX_FADV_DONTNEED | Evict the range from the page cache. On Linux, dirty pages are written back first; clean pages are freed immediately. Use after a sequential scan to avoid polluting the cache. |
| POSIX_FADV_NOREUSE | Pages will be accessed once. On Linux this is currently a no-op; FreeBSD implements it as a hint to prefer sequential access. |
Errors you will actually hit
Example
#include <fcntl.h>
#include <unistd.h>
/* warm the next chunk before processing the current one */
posix_fadvise(fd, next_offset, chunk_size, POSIX_FADV_WILLNEED);
process_chunk(buf, chunk_size);
/* evict the chunk just consumed so it does not pollute the LRU */
posix_fadvise(fd, cur_offset, chunk_size, POSIX_FADV_DONTNEED);BSD equivalent
FreeBSD: posix_fadvise(2) since FreeBSD 9.0; POSIX_FADV_NOREUSE is implemented as a sequential-access hint. OpenBSD does not implement posix_fadvise; use madvise(2) on mmap-ed regions instead.
Sources
Version numbers are read off the cited man pages, not memory. Spot one that's wrong? Tell Rod.