12.2. 使用 mlock ()系统调用锁定页面
实时 mlock ()
调用使用 addr
参数指定地址范围的开头,并使用 len
定义地址空间长度(以字节为单位)。alloc_workbuf ()
函数动态分配内存缓冲区并锁定它。内存分配由 posix_memalig ()
函数执行,以将内存区域与页面匹配。功能 free_workbuf ()
解锁内存区域。
先决条件:
-
您有 root 权限或
CAP_IPC_LOCK
功能在大型缓冲区上使用mlockall ()
或mlock ()
流程
要使用
mlock()
锁定页面,请运行以下命令:#include <stdlib.h> #include <unistd.h> #include <sys/mman.h> void *alloc_workbuf(size_t size) { void ptr; int retval; // alloc memory aligned to a page, to prevent two mlock() in the same page. retval = posix_memalign(&ptr, (size_t) sysconf(_SC_PAGESIZE), size); // return NULL on failure if (retval) return NULL; // lock this buffer into RAM if (mlock(ptr, size)) { free(ptr); return NULL; } return ptr; } void free_workbuf(void *ptr, size_t size) { // unlock the address range munlock(ptr, size); // free the memory free(ptr); }
#include <stdlib.h> #include <unistd.h> #include <sys/mman.h> void *alloc_workbuf(size_t size) { void ptr; int retval; // alloc memory aligned to a page, to prevent two mlock() in the same page. retval = posix_memalign(&ptr, (size_t) sysconf(_SC_PAGESIZE), size); // return NULL on failure if (retval) return NULL; // lock this buffer into RAM if (mlock(ptr, size)) { free(ptr); return NULL; } return ptr; } void free_workbuf(void *ptr, size_t size) { // unlock the address range munlock(ptr, size); // free the memory free(ptr); }
Copy to Clipboard Copied!
验证
实时 mlock ()
和 munlock ()
调用成功时返回 0。如果出现错误,则返回 -1 并设置 errno
来指示错误。