首页 > 解决方案 > Windows 进程和 WSL Linux 进程之间的共享内存

问题描述

我想使用共享内存技术在进程之间共享数据。我可以分别在 Windows 和 WSL(Linux 的 Windows 子系统)上使用 boost 库来做到这一点。两者都工作得很好。我的工作是让这些脚本在 1 个进程在 Windows 上运行并且 1 个进程在 WSL Linux 上运行时运行。它们在同一台机器上运行。

发件人脚本

#include <chrono>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <cstring>
#include <iostream>
#include <thread>
using namespace boost::interprocess;
int main(int argc, char* argv[])
{
   //Remove shared memory on construction and destruction
   struct shm_remove
   {
      shm_remove() { shared_memory_object::remove("sharedmem"); }
      ~shm_remove() { shared_memory_object::remove("sharedmem"); }
   } remover;

   //Create a shared memory object.
   shared_memory_object shm(create_only, "sharedmem", read_write);

   //Set size
   shm.truncate(1000);

   //Map the whole shared memory in this process
   mapped_region region(shm, read_write);

   //Write all the memory to 2 (to validate in listener script)
   std::memset(region.get_address(), 2, region.get_size());

   std::cout << "waiting before exit" << std::endl;
   std::this_thread::sleep_for(std::chrono::seconds(10));
   std::cout << "exited with success.." << std::endl;
   return 0;
}

侦听器脚本

#include <chrono>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <thread>
using namespace boost::interprocess;
int main(int argc, char* argv[])
{
   std::cout << "start read thread" << std::endl;
   
   //Open already created shared memory object.
   shared_memory_object shm(open_only, "sharedmem", read_only);

   //Map the whole shared memory in this process
   mapped_region region(shm, read_only);

   //Check that memory was initialized to 1
   char* mem = static_cast<char*>(region.get_address());
   for (std::size_t i = 0; i < region.get_size(); ++i)
      if (*mem++ != 2)
         return 1;   //Error checking memory

   std::cout << "exited with success.." << std::endl;
   return 0;
}

要单独在 Windows/Linux 中运行,

./sender

然后运行

./listener

从发送者创建共享内存,然后侦听器读取该内存。使用 boost 1.72.0 测试。应该与 boost 1.54 及更高版本一起使用。在 WSL-1 和 WSL-2 Ubuntu-1804 上测试。

问题是如何让发送者在 Windows 上工作,而监听者在 WSL Linux 上工作。这样我就可以在 Windows 和 Linux 系统之间共享内存。

提前致谢。

标签: c++boostipcwindows-subsystem-for-linuxwsl-2

解决方案


通过让 Windows 进程和 WSL1 进程都使用相同的文件来备份共享内存,可以在 Windows 进程和 WSL1 进程之间共享内存。


推荐阅读