Search code examples
androidlinux-kernelmmapmemory-mapped-files

How to manage memory usage of mmap on Linux Platforms?


I've been trying to use mmap for reading a relatively large file in a reasonable time. I know mumap method; but my question is that as long as i use the file i want it to be mapped in my process space; and in the meantime, whenever my process starts running out of space due to loading too many pages into RAM from that file; i want them to be swapped with new pages(or want them to be swapped with lru pages) without causing any problem at all. Does Kernel's internal memory management module handle that swapping on my behalf or its my responsibility to remove them(and if so, how? mumap?)? Please take these followings into consideration :

My platform is android(which is also a sort of linux platform), i only want to read pages; but no write at all(O_RDONLY and PROT_READ), i use MAP_SHARED for it might be shared by all other processes(In fact, there will be only one process to read :)).

Thanks in advance.


Solution

  • The Linux memory manager will handle dropping pages from your mapping and faulting them back in on-demand, you don't need to do anything special. Mapping as PROT_READ and MAP_SHARED is also helpful, because then the pages will be clean - the kernel won't need to write the physical pages out, it can simply drop them.

    If you want to assist the kernel, you can tell it the pages that you will and won't need soon using madvise() with the MADV_WILLNEED and MADV_DONTNEED flags respectively.