编辑 还尝试了 boost 1.75
我正在学习如何使用 boost::进程间消息队列,
我正在使用文档 here 中的示例
与一个不同的 - 对于我正在使用的另一个进程 fork()
但我越来越
boost::interprocess_exception::library_error
当我尝试从队列中读取时; 我在 Centos 7.6 上运行 boost 1.58
这是我的代码:
#include <iostream>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <vector>
[[no_discard]]bool RunChiled()
{
using namespace boost::interprocess;
try {
message_queue mq(open_or_create //open or create
, "message_queue" //name
, 100 //max message number
, 100 //max message size
);
message_queue::size_type recvd_size;
unsigned int priority = 0;
for (auto num = 0; num < 100; ++num) {
int number = 0;
mq.try_receive(&number, sizeof(int), recvd_size, priority);
if (number != num || recvd_size != sizeof(number))
return 1;
}
}catch(interprocess_exception &ex) {
message_queue::remove("message_queue");
std::cout << ex.what() << std::endl;
return 1;
}
message_queue::remove("message_queue");
return true;
}
int main() {
using namespace boost::interprocess;
message_queue::remove("message_queue");
auto pid = fork();
if(pid > 0)
{
sleep(2);
auto res = RunChiled();
std::cout << res;
} else if(pid == 0)
{
boost::interprocess::message_queue mq(create_only,"message_queue", 100, 100);
for(int i=0; i<100; ++i)
mq.send(&i,sizeof(i),0);
}
return 0;
}
最佳答案
查看代码here ,要接收的传递缓冲区必须至少与 max_msg_size 一样大(在您的情况下为 100)。
关于c++ - 尝试使用 boost::interprocess::message_queue 时出现 library_error 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66338663/