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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With