c++ - 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 系统之间共享内存。
提前致谢。
解决方案
通过让 Windows 进程和 WSL1 进程都使用相同的文件来备份共享内存,可以在 Windows 进程和 WSL1 进程之间共享内存。
推荐阅读
- python - 使用 OpenSSH4.3 的服务器丢失 Paramiko ssh 横幅
- git - 将主分支设置为初始状态?
- flutter - Fluttter Web 应用程序不适用于本地 golang http 服务器
- stripe-payments - Apple Pay Web & Stripe:如何自定义 Apple Pay 按钮
- python - 将 DataFrame 列转换为 json 列
- c - 当行超过 100 个字符时,fprintf 会生成一个 utf-16 文本文件
- css - 如何防止 Outlook 中 HTML 模板中的图像使用 React 进行不必要的扩展?
- flutter - 使用 .aar 模块的 Flutter 插件在示例应用程序中构建和运行良好,但无法在其他应用程序中构建
- java - 我写了一个二分搜索,但有一些错误
- drake - MultiBodyPlant 上下文中带有 nans 的额外主体在模拟时导致错误