Mel*_*Dal 6 c++ boost ipc windows-subsystem-for-linux wsl-2
我想使用共享内存技术在进程之间共享数据。我可以分别在 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;
}
Run Code Online (Sandbox Code Playgroud)
侦听器脚本
#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;
}
Run Code Online (Sandbox Code Playgroud)
要单独在 Windows/Linux 中运行,
./sender
Run Code Online (Sandbox Code Playgroud)
然后运行
./listener
Run Code Online (Sandbox Code Playgroud)
从发送方创建共享内存,然后侦听器读取该内存。使用 boost 1.72.0 进行测试。应该与 boost 1.54 和更高版本一起使用。在 WSL-1 和 WSL-2 Ubuntu-1804 上测试。
问题是如何让发件人在 Windows 上工作,而侦听器在 WSL Linux 上工作。这样我就可以在 Windows 和 Linux 系统之间共享内存。
提前致谢。