Does Linux map a virtual memory range to an existing virtual memory range?

On Linux, is there a way (in user space) to map a range of virtual addresses to physical pages that support an existing range of virtual addresses? The mmap () function allows you to display files or "new" physical pages. I need 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
+3
source share
3 answers

I was curious, so I tested the idea of ​​shared memory suggested in the 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;
}

(, )

+3

fd , addr1, mmap addr2.

Linux remap_file_pages VMA , .

+1

/proc/self/mem mmap .

-1

Source: https://habr.com/ru/post/1779520/


All Articles