且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

共享内存附加进程计数。

更新时间:2023-09-13 17:34:16

如果在获得计数后立即附加新进程并且想要销毁共享内存之前该怎么办?


根据文档,
"文件映射对象的映射视图维护内部引用到对象,文件映射对象不会关闭,直到所有对它的引用都被释放"。因此,您无需检查计数。



Hello,

I want to use shared memory in my application. I have created shared memory and successfully using between 2 processes. 

I want to know how many (only count) processes attached to shared memory. So if only 1 process is attached to shared memory then I want to destroy shared memory.

API used to create and destroy shred Memory ->

char key_name [50] = {0};
snprintf(key_name, 50, "Global\\%d",key);

mMemId = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,size,key_name);

mMem = MapViewOfFile(mMemId, FILE_MAP_ALL_ACCESS, 0, 0, size);

UnmapViewOfFile(mMem);
CloseHandle(mMemId);

What if a new process is attached just after you get the count and before you want to destroy the shared memory?

According to documentation, "mapped views of a file mapping object maintain internal references to the object, and a file mapping object does not close until all references to it are released". Therefore, you do not have to check the count.