确定文件映射到内存的次数 [英] Determine how many times file is mapped into memory

查看:84
本文介绍了确定文件映射到内存的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux中是否可以获取特定文件描述符上的内存映射总数?为了清楚起见,我编写了一个小的示例代码来说明如何打开/创建内存映射:

Is it possible to get the total amount of memory maps on a specific file descriptor in Linux? For clearness I made a small example code how I open/create the memory map:

int fileDescriptor = open(mapname, O_RDWR | O_CREAT | O_EXCL, 0666);
if(fileDescriptor < 0)
    return false;

//Map Semaphore
memorymap = mmap(NULL, sizeof(mapObject), PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor, 0);
close(fileDescriptor); 

内存映射由多个进程使用.我可以访问将要使用此内存映射的其他进程的代码库.如何以100%正确的方式获取fileDescriptor上有多少张地图?

The memory map is used by multiple processes. I have access to the code base of the other processes that are going to use this memory map. How can I get in a 100% correct way how many maps there are on the fileDescriptor?

推荐答案

您可以检查所有/proc/*/maps文件并计算提及内存映射文件的次数.

You can check all the /proc/*/maps files and count the number of times the memory-mapped file is mentioned.

例如,这就是提到内存映射"/tmp/delme"的方式

For example, this is how the memory mapped "/tmp/delme" is mentioned

7fdb737d0000-7fdb737d1000 rw-s 00000000 08:04 13893648                   /tmp/delme
7fdb737d8000-7fdb737d9000 rw-s 00000000 08:04 13893648                   /tmp/delme

使用以下代码时:

// g++ -std=c++11 delme.cc && ./a.out
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fstream>
#include <iostream>

int main() {
  int fileDescriptor = open("/tmp/delme", O_RDWR, 0664);
  if (fileDescriptor < 0) return false;
  auto memorymap = mmap (NULL, 123, PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor, 0);
  auto memorymap2 = mmap (NULL, 123, PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor, 0);
  close (fileDescriptor);
  std::ifstream mappings ("/proc/self/maps");
  std::cout << mappings.rdbuf() << std::endl;
}

另请参见了解Linux/proc/id/maps .

如果您发出全局锁定,以防止在进行计数时发生任何映射和未映射,则此计数器将是 100%正确.

If you issue a global lock, preventing any mappings and unmappings from happening while the counting is taking the place, then this counter will be 100% correct.

这篇关于确定文件映射到内存的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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