Linux Stop Flushing of mmaped Pages To Disk

In Linux, the behavior of flushing mmapped pages to disk can be controlled using the madvise() system call. This system call allows you to specify the behavior of the kernel when it comes to writing out the pages of a file that are mapped into memory using mmap().

To stop flushing of mmapped pages to disk, you can use the MADV_DONTNEED flag with madvise(). This flag tells the kernel to not write the pages back to disk, even if they have been modified.

Here is an example of how you can use madvise() in a C program to stop flushing of mmapped pages to disk:

#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main() {
int fd;
char *data;

fd = open(“file.txt”, O_RDWR);
data = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
madvise(data, 4096, MADV_DONTNEED);
close(fd);
return 0;
}

Note that this technique is only applicable to files that are mapped into memory using mmap(). Regular file I/O is still subject to the normal disk write-back behavior.

Leave a Comment