Skip to content

Instantly share code, notes, and snippets.

@filosofisto
Last active December 29, 2017 13:31
Show Gist options
  • Save filosofisto/4a59e81bfd7093d8f04cb643e2a1777c to your computer and use it in GitHub Desktop.
Save filosofisto/4a59e81bfd7093d8f04cb643e2a1777c to your computer and use it in GitHub Desktop.
Message Queue Posix standart.Sample of mq_receive.Tested in Linux OpenSUSE and Solaris 5.11.
cmake_minimum_required(VERSION 3.9)
project(posix_mq_receive)
set(CMAKE_CXX_STANDARD 98)
set(GCC_COVERATE_LINK_FLAGS "-lrt")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERATE_LINK_FLAGS}")
add_executable(posix_mq_receive main.cpp)
#include <iostream>
#include <cstdlib>
#include <mqueue.h>
#include <errno.h>
#include <cstring>
#ifdef sun
#include <fcntl.h>
#endif
using namespace std;
int main(int argc, char **argv) {
cout << "Message Posix Receive Sample" << endl;
mqd_t queue;
struct mq_attr attr;
ssize_t bytes;
char *buffer;
queue = mq_open("/mq_test", O_RDONLY, S_IRUSR|S_IWUSR, NULL);
if (queue == static_cast<mqd_t>(-1)) {
cerr << "Error on open queue mq_test: "
<< strerror(errno)
<< endl;
return EXIT_FAILURE;
}
if (mq_getattr(queue, &attr) == -1) {
cerr << "Error on get attributes on mq_test: "
<< strerror(errno)
<< endl;
return EXIT_FAILURE;
}
cout << "Message opened success" << endl;
buffer = (char *) malloc(attr.mq_msgsize);
if (buffer == NULL) {
cerr << "Memory exausted: "
<< strerror(errno)
<< endl;
return EXIT_FAILURE;
}
bytes = mq_receive(queue, buffer, attr.mq_msgsize, NULL);
if (bytes == -1) {
cerr << "Error on receive data to queue: "
<< strerror(errno)
<< endl;
return EXIT_FAILURE;
}
cout << "Message readed in queue:"
<< buffer
<< endl;
if (mq_close(queue) == -1) {
cerr << "Error on close queue: "
<< strerror(errno)
<< endl;
return EXIT_FAILURE;
}
cout << "Message close success" << endl;
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment