简体   繁体   English

Linux将虚拟内存范围映射到现有虚拟内存范围?

[英]Linux mapping virtual memory range to existing virtual memory range?

In Linux, is there a way (in user space) to map a virtual address range to the physical pages that back an existing virtual address range? 在Linux中,有没有办法(在用户空间中)将虚拟地址范围映射到支持现有虚拟地址范围的物理页面? The mmap() function only allows one to map files or "new" physical pages. mmap()函数只允许映射文件或“新”物理页面。 I need to be able to do something like this: 我需要能够做这样的事情:

int* addr1 = malloc(SIZE);
int* addr2 = 0x60000;      // Assume nothing is allocated here
fancy_map_function(addr1, addr2, SIZE);
assert(*addr1 == *addr2);  // Should succeed
assert(addr1 != addr2);    // Should succeed

I was curious so I tested the shared memory idea suggested in question comments, and it seems to work: 我很好奇所以我测试了问题评论中提出的共享内存想法,它似乎工作:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <assert.h>

#define SIZE 256
int main (int argc, char ** argv) {
  int fd;
  int *addr1, *addr2;

  fd = shm_open("/example_shm", O_RDWR | O_CREAT, 0777);
  ftruncate( fd, SIZE);
  addr1 = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  addr2 = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

  printf("addr1 = %p addr2 = %p\n", addr1, addr2);
  *addr1 = 0x12345678;
  assert(*addr1 == *addr2);  // Should succeed
  assert(addr1 != addr2);    // Should succeed

  return 0;
}

(Obviously real code will want to check the return value of the syscalls for errors and clean up after itself) (显然,实际代码需要检查系统调用的返回值是否存在错误,并在自身后进行清理)

If you have the fd for the file mapped at addr1 , you can simply mmap it again at addr2 . 如果你有addr1映射文件的fd,你可以在addr2再次mmap它。

Otherwise, the Linux-specific remap_file_pages can modify the virtual address ⇆ file offset translation within a single VMA, with page-sized granularity, including mapping the same file offset to multiple addresses. 否则,特定于Linux的remap_file_pages可以在单个VMA中修改虚拟地址⇆文件偏移量转换,具有页面大小的粒度,包括将相同的文件偏移量映射到多个地址。

打开/proc/self/memmmap您需要的虚拟地址范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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