posix_fadvise(2) -- Linux man page



posix_fadvise - predeclare an access pattern for file data  


#include <fcntl.h>

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


Programs can use posix_fadvise to announce an intention to access file data in a specific pattern in the future, thus allowing the kernel to perform appropriate optimisations.

The advice applies to a (not necessarily existent) region starting at offset and extending for len bytes (or until the end of the file if len is 0) within the file referred to by fd. The advice is not binding; it merely constitutes an expectation on behalf of the application.

Permissible values for advice include:

Indicates that the application has no advice to give about its access pattern for the specified data. If no advice is given for an open file, this is the default assumption.
The application expects to access the specified data sequentially (with lower offsets read before higher ones).
The specified data will be accessed in random order.
The specified data will be accessed only once.
The specified data will be accessed in the near future.
The specified data will not be accessed in the near future.


On success, zero is returned. On error, -1 is returned, and errno is set appropriately.  


The fd argument was not a valid file descriptor.
An invalid value was specified for advice.
The specified file descriptor refers to a pipe or FIFO. (Linux actually returns EINVAL in this case.)


Under Linux, POSIX_FADV_NORMAL sets the readahead window to the default size for the backing device; POSIX_FADV_SEQUENTIAL doubles this size, and POSIX_FADV_RANDOM disables file readahead entirely. These changes affect the the entire file, not just the specified region (but other open file handles to the same file are unaffected).

POSIX_FADV_WILLNEED and POSIX_FADV_NOREUSE both initiate a non-blocking read of the specified region into the page cache. The amount of data read may be decreased by the kernel depending on VM load. (A few megabytes will usually be fully satisfied, and more is rarely useful.)

POSIX_FADV_DONTNEED attempts to free cached pages associated with the specified region. This is useful, for example, while streaming large files. A program may periodically request the kernel to free cached data that has already been used, so that more useful cached pages are not discarded instead.

Pages that have not yet been written out will be unaffected, so if the application wishes to guarantee that pages will be released, it should call fsync or fdatasync first.  


SUSv3 (Advanced Realtime Option), POSIX 1003.1-2003. Note that the type of the len parameter was changed from size_t to off_t in POSIX 1003.1-2003 TC5.  


posix_fallocate(2), posix_madvise(2).