Linux将虚拟内存范围映射到现有虚拟内存范围? [英] Linux mapping virtual memory range to existing virtual memory range?

查看:60
本文介绍了Linux将虚拟内存范围映射到现有虚拟内存范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux中,是否有一种方法(在用户空间中)将虚拟地址范围映射到支持现有虚拟地址范围的物理页?mmap()函数仅允许一个映射文件或新"物理页面.我需要能够执行以下操作:

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? The mmap() function only allows one to map files or "new" physical pages. 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;
}

(显然,实际的代码将要检查syscalls的返回值是否有错误,并自行清除)

(Obviously real code will want to check the return value of the syscalls for errors and clean up after itself)

这篇关于Linux将虚拟内存范围映射到现有虚拟内存范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆