将内存锁定到 C 中的物理 RAM 以用于动态分配指针

Lock the memory to physical RAM in C for the dynamically allocate pointer

我想使用 mlockmunlock 将内存锁定到 C 中的物理 RAM,但我不确定正确的用法。

请允许我逐步解释:

假设我使用 calloc:

动态分配一个指针
char * data = (char *)calloc(12, sizeof(char*));

我应该在那之后立即mlock吗?

我们还假设我稍后尝试使用 realloc:

调整内存块的大小
(char *)realloc(data, 100 * sizeof(char*));

注意上面的增加量(100)是随机的,有时我会减少内存块。

我是否应该先执行 munlock 然后再执行 mlock 以解决所做的更改?

另外,当我稍后想释放指针 data 时,我应该先 munlock 吗?

我希望有人能向我解释正确的步骤,以便我更好地理解。

来自mlock() and munlock()的POSIX规范:

The mlock() function shall cause those whole pages containing any part of the address space of the process starting at address addr and continuing for len bytes to be memory-resident until unlocked or until the process exits or execs another process image. The implementation may require that addr be a multiple of {PAGESIZE}.

The munlock() function shall unlock those whole pages containing any part of the address space of the process starting at address addr and continuing for len bytes, regardless of how many times mlock() has been called by the process for any of the pages in the specified range. The implementation may require that addr be a multiple of {PAGESIZE}.

注意:

  • 这两个功能都适用于整个页面
  • 这两个函数可能需要 addr 是页面大小
  • 的倍数
  • munlock 不使用任何引用计数来跟踪锁生命周期

这几乎不可能将它们与 malloc/calloc/realloc 编辑的指针 return 一起使用,因为它们可以:

  • 不小心 lock/unlock 附近的页面(您可能会不小心解锁必须驻留在内存中的页面)
  • 可能return指针不适合那些函数

您应该改用 mmap 或任何其他 OS 特定的机制。例如 Linux 有 mremap 允许你 "reallocate" 内存。无论您使用什么,请确保 mlock 行为是明确定义的。来自 Linux man 页:

If the memory segment specified by old_address and old_size is locked (using mlock(2) or similar), then this lock is maintained when the segment is resized and/or relocated. As a consequence, the amount of memory locked by the process may change.


注意Nate Eldredge's下面的评论:

Another problem with using realloc with locked memory is that the data will be copied to the new location before you have a chance to find out where it is and lock it. If your purpose in using mlock is to ensure that sensitive data never gets written out to swap, this creates a window of time where that might happen.

TL;DR

  1. 内存锁定不与使用 C 语言运行时的通用内存分配混合。

  2. 内存锁定确实与面向页面的虚拟内存映射 OS 级 API 混合。

  3. 除非出现特殊情况,否则上述内容成立(这是我的出路:)