C++ – Determines the number of times a file is mapped to memory

Determines the number of times a file is mapped to memory… here is a solution to the problem.

Determines the number of times a file is mapped to memory

Is it possible to get the total amount of memory maps on a particular file descriptor in Linux? For clarity, I wrote a little sample code to open/create a 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); 

Memory mapping is used by multiple processes. I have access to the codebase of other processes that will use this memory map. How do I get how many maps are on my fileDescriptor in a 100% correct way?

Solution

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

For example, the memory map “/tmp/delme” is mentioned like this

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 that prevents any mapping and unmapping from occurring while the count occurs, this counter will be 100% correct.

Related Problems and Solutions