将共享内存与 CreateFileMapping 和 MapViewofFile 一起使用的问题
我有两个关于使用共享内存的问题。我正在使用 CreateFileMapping 在两个进程之间创建共享内存区域。
1)我知道我需要对从 CreateFileMapping 或 OpenFileMapping 调用返回的每个句柄调用 CloseHandle 才能释放内存。我的问题是,如果使用共享内存的程序在未调用 CloseHandle 的情况下退出,Windows XP/7 是否会正确关闭所有句柄并释放内存? IE - 在所有使用内存的进程都关闭后,是否存在内存泄漏的可能性?
2)我使用MapViewofFile来获取指向内存的指针。在一个实例中,我假设共享内存将始终存在于方法的上下文中。因此,我将 MapViewOfFile 的返回值保存为指针,并关闭了内存的句柄,并且仅使用指向共享内存的指针(但仍锁定对其的访问)。这是安全的,还是应该在每次访问共享内存时调用 MapViewOfFile?
谢谢,
伊恩
I have 2 questions concerns about using shared memory. I'm using CreateFileMapping to create a shared memory area between two processes.
1) I understand that I need to call CloseHandle on every handle returned from a CreateFileMapping or OpenFileMapping call in order to release the memory. My question is, do all handles get closed appropriately and mem deallocated by Windows XP/7 if the programs using the shared memory exit without calling CloseHandle? IE - is there a possibility of a mem leak after all processes using the mem have been closed?
2) I use MapViewofFile to get a pointer to the mem. In 1 instance I've assumed that the shared memory will always exist in the context of a method. So I've saved the return value of MapViewOfFile as a pointer and closed the handle to the mem and am just using the pointer to the shared mem (but still locking access to it). Is this safe, or should I call MapViewOfFile every time I access the shared mem?
Thanks,
Ian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1)是的,当进程终止时,所有句柄都会关闭,无论它是否终止或顺利完成。这里没有泄漏。
2) 只要不调用
UnmapViewOfFile
,进程仍然可以访问内存,即使句柄已经关闭:1) Yes, all handles are closed when a process terminates, no matter if it dies or finishes nicely. No leaks here.
2) As long as you don't call
UnmapViewOfFile
, the memory will still be accesible to the process, even if the handle has been closed: