c++ - 尝试使用 boost::interprocess::message_queue 时出现 library_error 异常

标签 c++ boost c++17 boost-interprocess

编辑 还尝试了 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/

相关文章:

c++ - 如何从多索引中获取值

c++ - 使用 boost::phoenix 适配 BOOST_CHECK 宏

c++ - 具有自动类型返回扣除的模板

C++17 检查有效表达式

c++ - 将函数传递给可变函数模板

android - opencv C++ 从 android NV21 图像数据缓冲区创建 Mat 对象

c++ - Windows 7 shell 函数的链接问题

c++ - 如何使用 json 解析器的 boost property_tree 创建空数组节点

c++ - 简单的字符串比较如何导致 OleException?

c# - 一元加号运算符有什么作用?