我在我的 Linux 用户空间应用程序中分配了一些内存。但是,此内存尚未得到物理内存的支持。
为了使页面被映射,我尝试读取该区域中的每个页面,如下所示。但它并不总是对我有用。
这是我的原始代码:
void Function(void)
{
char *memory;
memory = malloc(4096 * 10);
}
这样分配的,虚拟内存还没有映射到物理内存。
所以我修改了代码:
void Function(void)
{
char *memory;
volatile uint *accessMemory;
memory = malloc(4096 * 10);
accessMemory = (volatile uint *)memory;
for (i = 0; i < 4096 / 10; i++) {
printf("%X\n", *accessMemory);
accessMemory = (volatile uint *)((uint)accessMemory + 4096);
}
}
但是我还是遇到了同样的问题。我做错了什么?
最佳答案
你的代码有一个明显的问题,转换是一个症状。您为 40960 个字符分配空间,但随后尝试访问无符号 409 个无符号整数,每个整数相隔 4096 个。不仅如此,您还会在执行算术运算之前将指针强制转换为 uint - 这很可能是一种缩小转换,而且绝对不安全。
最好将 memory
指针声明为您打算使用它的类型:
const size_t page_size = 4096; // TODO: get actual value from system
uint *memory;
uint *end;
volatile uint *p;
memory = malloc(page_size * 10 * sizeof *memory);
end = memory + page_size * 10;
for (p = memory; p < end; p += 4096/(sizeof *p))
printf("%X\n", *p);
话虽如此,如果您希望在页面方面工作,那么使用 mmap()
可能会更好;特别是这个选项:
MAP_POPULATE (since Linux 2.5.46)
Populate (prefault) page tables for a mapping. For a file mapping, this causes read-ahead on the file. Later accesses to the mapping will not be blocked by page faults. MAP_POPULATE is supported for private mappings only since Linux 2.6.23.
关于c - 如何立即调入新分配的虚拟内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600114/