Determine how many times file is mapped into memory

亡梦爱人 提交于 2019-12-03 21:02:41
ArtemGr

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

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

when using the following code:

// 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;
}

See also Understanding Linux /proc/id/maps.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!