Themlockall
function locks all of the pages mapped by aprocess's address space.On a successful call tomlockall
, the specified process becomes locked andmemory-resident.Themlockall
function takes two flags,MCL_CURRENT and MCL_FUTURE, which determine whether the pages to be lockedare those currently mapped, or if pages mapped in the future are to belocked.You must specify at least one flag for themlockall
function to lock pages.If you specify bothflags, the address space to be locked is constructed from the logical OR ofthe two flags.
If you specify MCL_CURRENT only, all currently mapped pages of the process'saddress space are memory-resident and locked.Subsequent growth in any areaof the specified region is not locked into memory.If you specify theMCL_FUTURE flag only, all future pages are locked in memory.If you specifyboth MCL_CURRENT and MCL_FUTURE, then the current pages are locked andsubsequent growth is automatically locked into memory.
简言之,MCL_CURRENT 就是会Lock住当前驻留内存的页,MCL_FUTURE会Lock住将来会驻留内存的页,比如后面有malloc的处理时,malloc的空间也不会交换到swap分区。
示例:
Example 4-2: Using the mlockall Function
#include <unistd.h> /* Support all standards */
#include <stdlib.h> /* malloc support */
#include <sys/mman.h> /* Memory locking functions */
#define BUFFER 2048
main()
{
void *p[3]; /* Array of 3 pointers to void */
p[0] = malloc(BUFFER);
/* Currently no memory is locked */
if ( mlockall(MCL_CURRENT) == -1 )
perror("mlockall:1");
/* All currently allocated memory is locked */
p[1] = malloc(BUFFER);
/* All memory but data pointed to by p[1] is locked */
if ( munlockall() == -1 )
perror("munlockall:1");
/* No memory is now locked */
if ( mlockall(MCL_FUTURE) == -1 )
perror("mlockall:2");
/* Only memory allocated in the future */
/* will be locked */
p[2] = malloc(BUFFER);
/* Only data pointed to by data[2] is locked */
if ( mlockall(MCL_CURRENT|MCL_FUTURE) == -1 )
perror("mlockall:3");
/* All memory currently allocated and all memory that */
/* gets allocated in the future will be locked */
}