您可以检查所有/proc/*/maps
文件并计算内存映射文件被提及的次数。
例如,内存映射“/tmp/delme”是这样提到的
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 https://stackoverflow.com/questions/1401359/understanding-linux-proc-id-maps.
如果您发出全局锁,以防止在计数发生时发生任何映射和取消映射,则该计数器将是100%正确.