c++boostc++17boost-interprocess

getting library_error exception when trying to use boost::interprocess::message_queue


EDIT also tried with boost 1.75

I'm learning how to use boost::interprocess message queue, I'm using the example from the documentation here with one different - for the other process I'm using fork() but I'm getting

boost::interprocess_exception::library_error

when I'm trying to read from the queue; I'm running boost 1.58 over Centos 7.6

this is my code:

#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;
}

Solution

  • Looking at the code here, the passed buffer to receive must be at least as big as max_msg_size (100, in your case).