4

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); 

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?

lauw
  • 1,301
  • 2
  • 10
  • 10
  • Is it only going to be your processes that are opening the file? – Fantastic Mr Fox Jul 03 '14 at 06:12
  • @Ben There are multiple processes that are going to use the file. – lauw Jul 03 '14 at 11:33
  • Are all the processes owned by you? As in do you have the option to edit the code for anything that is accessing the file? – Fantastic Mr Fox Jul 03 '14 at 22:38
  • @Ben All those process are owned by me. I have full access to the code of all the programs that are going to use this. – lauw Jul 04 '14 at 06:38
  • I guess what i am getting at is can you make a short application that accepts socket connections from each of the applications that access the file. Then when they access it they connect this "other" program which tallies up its connections? – Fantastic Mr Fox Jul 04 '14 at 06:39
  • @lauw When you're giving a code example, it is always better to make it *complete*, if possible (http://stackoverflow.com/help/mcve). – ArtemGr Jul 05 '14 at 13:31

1 Answers1

5

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.

Community
  • 1
  • 1
ArtemGr
  • 11,684
  • 3
  • 52
  • 85