c++ - 无法释放由 C++ 中的 CreateFileMapping 和 MapViewOfFile 创建的共享内存

标签 c++ shared-memory

我正在学习使用 C++ 中的共享内存。我发现在 Windows 下我需要使用 CreateFileMapping 和 MapViewOfFile 函数。我想共享 char 数组,所以我的部分代码是:

HANDLE hBuffer = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, bufferName);
char * buffer = (char *) MapViewOfFile(hBuffer, FILE_MAP_ALL_ACCESS, 0, 0, size);

(当然会检查 NULL)并在使用共享内存结束时调用:

UnmapViewOfFile(buffer); // returned true
CloseHandle(hBuffer); // returned true also

但是在资源监视器中我可以看到没有释放内存。多次调用时,应用程序分配的内存在增加,但没有释放。我究竟做错了什么?还是有其他释放共享内存的函数?

感谢您的回答。

最佳答案

感谢 marcin_j 解决了问题:

Your code looks find (well,... you mispelled HANDLE), you can use procexp.exe from sysinternals to find your HANDLE by name (if it is not found then it was closed), also observe on Performance tab how Virtual Size of you app changes, there is also Handles count that should change accordingly.

Also, observe what will happen after you execute memset(buffer,0,size); after MapViewOfFile - this is actually when system will commit memory and when your workin set will rise.

My above comment is wrong, CreateFileMapping by default applies SEC_COMMIT which commits memory. But I suppose your memory is paged until memset is called, after that call paged pages are moved to physical memory, which rises working set.... if I am not wrong...

关于c++ - 无法释放由 C++ 中的 CreateFileMapping 和 MapViewOfFile 创建的共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21588980/

相关文章:

c++ - 探查器输出中线程并发开销时间的含义是什么?

c - 访问共享内存中的结构成员 "in C"

python - 如何在线程之间共享对象?

C静态变量和linux fork

c - 命名信号量只是不工作

c++ - 使用 MapViewOfFile 分配静态共享内存

c++ - QVector 与 QList

c++ - 为什么编译器看不到这个函数头?

C++ 如何区分 std::cin 和 std::ifstream?

c++ - Eigen 表达式调试