c++ - boost::Managed_shared_memory 是否使用我硬盘上的文件?

标签 c++ boost shared-memory boost-interprocess

当我创建一个新的 boost::interprocess::managed_shared_memory 时,我可以看到一个文件出现在 C:\ProgramData\boost_interprocess\1571641094\NAME_OF_SHARED_MEMORY 中,其大小似乎以匹配创建的共享内存。

我对documention的理解是有两个广泛使用的对象可用于在进程之间共享内存(在 managed_shared_memory 的范围内):

  • 基本托管共享内存
  • basic_management_mapped_file

managed_shared_memory 使用basic_management_shared_memory 实现。我认为此实现是正确的共享内存,而不是内存映射文件

看到它使用一个文件让我很困惑。这两个托管共享内存都是基于内存映射文件实现吗?

Windows 上唯一避免内存映射文件的 boost 共享内存解决方案是 windows_shared_memory 吗?

注意:我使用的是 Windows 10,在 VS2013 上使用 VC++。

使用managed_shared_memory时可以重现在ProgramData中创建文件的行为的代码示例:

#include <boost/interprocess/managed_shared_memory.hpp>

int main(int argc, char *argv[])
{
  boost::interprocess::permissions permissions;
  permissions.set_unrestricted();

  boost::interprocess::managed_shared_memory* sharedMemory;
  sharedMemory = new boost::interprocess::managed_shared_memory(
  {
    boost::interprocess::open_or_create,
    "NAME_OF_SHARED_MEMORY",
    400000,
    0,
    permissions
  }
  );

  return 0;
}

最佳答案

你的假设是正确的。 'Emulation for systems without shared memory objects Boost 文档中的部分解释了正在发生的事情:

Boost.Interprocess provides portable shared memory in terms of POSIX semantics. Some operating systems don't support shared memory as defined by POSIX:

  • Windows operating systems provide shared memory using memory backed by the paging file but the lifetime semantics are different from the ones defined by POSIX (see Native windows shared memory section for more information).

...

In those platforms, shared memory is emulated with mapped files created in a "boost_interprocess" folder created in a temporary files directory. In Windows platforms, if "Common AppData" key is present in the registry, "boost_interprocess" folder is created in that directory (in XP usually "C:\Documents and Settings\All Users\Application Data" and in Vista "C:\ProgramData"). For Windows platforms without that registry key and Unix systems, shared memory is created in the system temporary files directory ("/tmp" or similar).

Because of this emulation, shared memory has filesystem lifetime in some of those systems.

正如您已经指出的,作为替代方案,您可以使用 native windows shared memory对象(使用 windows_shared_memory )。它将使用页面文件支持的共享内存对象,而不是在 C:\ProgramData 中创建的文件。一般来说,这不会使用文件系统(请参阅: https://stackoverflow.com/a/6215317/79111 )。如果不考虑可移植性,这可能是一种更好的方法,因为它允许与使用共享内存但不依赖 Boost.Interprocess 的其他应用程序进行互操作。

关于c++ - boost::Managed_shared_memory 是否使用我硬盘上的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58487479/

相关文章:

c - 按名称列出 Solaris 上的共享内存对象

c++ - std::boost::asio::post/dispatch 使用哪个 io_context?

c++ - Linux下如何检测另一个进程并与其通信?

c++ - 如何有效地将具有可变长度成员的对象保存到二进制文件中?

c++ - 一个类自动生成序列化函数的宏

java - Java 中共享内存中值的原子获取和递增功能

c++ - 通过引用传递数组?

c++ - Qt 事件或 repaint() 函数不工作

c++ - 如何将 asio 与设备文件一起使用

android - 我可以在没有任何传递的情况下在 2 个进程之间共享内存吗? (在安卓 NDK 中)