简体   繁体   中英

In a POSIX unix system, is it possible to mmap() a file in such a way that it will never be swapped out to disk in favor of other files?

If not using mmap() , it seems like there should be a way to give certain files "priority", so that the only time they're swapped out is for page faults trying to bring in, eg, executing code, or memory that was malloc() 'd by some process, but never other files. One can think of situations where this could be useful. Consider search engines, which should keep their index files in cache, but which may be simultaneously writing new files (not being used for search).

There are a few ways.

The best way is with madvise() , which allows you to inform the kernel that you will need a particular range of memory soon, which gives it priority over other memory. You can also use it to say that a particular range will not be needed soon, so it should be swapped out sooner.

The hack way is with mlock() , which forces a range of memory to stay in RAM. This is generally not a good idea, and should only be used in special cases. The most common case is to store passwords in RAM so that the password cannot be recovered from the swap file after the computer is powered off. I would not use mlock() for performance tuning unless I had exhausted other options.

The worst way is to constantly poke memory, forcing it to stay fresh.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM