将共享内存与 CreateFileMapping 和 MapViewofFile 一起使用的问题

发布于 2024-12-22 07:52:16 字数 449 浏览 3 评论 0原文

我有两个关于使用共享内存的问题。我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪漫之都 2024-12-29 07:52:17

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:

Although an application may close the file handle used to create a file mapping object, the system holds the corresponding file open until the last view of the file is unmapped

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文