我怎么能检测出特定的页面是否在内存映射? [英] how can I detect whether a specific page is mapped in memory?

查看:198
本文介绍了我怎么能检测出特定的页面是否在内存映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测是否一个​​特定的页面已经映射到存储器中。这里的目标是能够调用MMAP具有固定存储器地址之前执行该检查。下面code说明了在这种情况下,在默认情况下会发生什么。MMAP默默地重新映射原来的内存页

I would like to detect whether or not a specific page has already been mapped in memory. The goal here is to be able to perform this check before calling mmap with a fixed memory address. The following code illustrates what happens in this case by default: mmap silently remaps the original memory pages.

#include <sys/mman.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
  int page_size;
  void *ptr;
  page_size = getpagesize();
  ptr = mmap(0, 10 * page_size, PROT_READ | PROT_WRITE,
             MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
  if (ptr == MAP_FAILED) {
    printf ("map1 failed\n");
    return 1;
  }
  ((int *)ptr)[0] = 0xdeadbeaf;
  ptr = mmap(ptr, 2 * page_size, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, 0, 0);
  if (ptr == MAP_FAILED) {
    printf ("map2 failed\n");
    return 1;
  }
  if (((int *)ptr)[0] != 0xdeadbeaf) {
    printf ("oops, data gone !\n");
  }
  return 0;
}

我明白,我可以打开和分析的/ proc /自/图找出哪些内存范围已分配和推断,如果我可以放心地请求特定的内存范围与MMAP但我要寻找一个合适的API:是有这样的事?

I understand that I could open and parse /proc/self/maps to figure out which memory range has been allocated and infer from that if I can safely request a specific memory range with mmap but I am looking for a proper API: is there such a thing ?

推荐答案

则msync(地址,LEN,0),检查ENOMEM似乎工作(具有相当肤浅的测试)。

msync(addr, len, 0) and checking for ENOMEM seems to work (with a fairly superficial test).

这篇关于我怎么能检测出特定的页面是否在内存映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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