我想使用共享内存技术在进程之间共享数据。我可以分别在Windows和WSL(Windows Linux子系统(上使用boost库来实现这一点。两者都很好。我的工作是当一个进程在Windows上运行,而一个进程正在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进行测试。应与增压1.54及更高版本配合使用。在WSL-1和WSL-2 Ubuntu-1804上进行了测试。
问题是如何让发送方在Windows上工作,而侦听器在WSL Linux上工作。这样我就可以在Windows和Linux系统之间共享内存。
提前谢谢。
通过让Windows进程和WSL1进程使用相同的文件来支持共享内存,可以在它们之间共享内存。