I am trying to set up message queue IPC example.
Problem: I am trying to make a working test case where I use mqueue to send a struct with various fields (I am referencing this post). However, I am running into Message too long error. Most examples send a char* message but I want to send a struct with multiple fields. In this toy example it just has a filepath but I would like to add other fields into the struct as well and send the struct over the message queue.
Working example:
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h> // mq_open(), mq_send(), mq_receive()
//#include <errno.h>
//#include <time.h>
#include <string.h> // strncpy(), strlen()
#include <stdio.h> // printf(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
#define MSG_SIZE (300)
static mqd_t mqdes = -1;
static struct mq_attr attr;
typedef struct{
char filepath[MSG_SIZE];
} obj;
void sendQueue()
{
obj obj1;
strncpy(obj1.filepath, "this_is_a_test", MSG_SIZE);
if( -1 == mq_send(mqdes, (const char *) &obj1, sizeof(obj1), 0) )
{
perror( "mq_send failed" );
exit( EXIT_FAILURE );
}
else
{
printf("msg sent successfully");
}
}
void recvQueue()
{
obj recv_obj;
ssize_t res = mq_receive(mqdes, (char*) &recv_obj, sizeof(recv_obj), NULL);
if (res == -1)
{
perror("mq_receive failed");
}
else
{
printf("Message: %s\n", recv_obj.filepath);
}
}
int main( void )
{
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
memset( &attr, 0x00, sizeof(struct mq_attr) );
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = 1024;
attr.mq_curmsgs = 0;
char *queueName = "/test";
mqdes = mq_open( queueName, O_RDWR|O_CREAT, mode, &attr);
if( -1 == mqdes )
{
perror( "mq_open failed");
exit( EXIT_FAILURE );
}
// implied else, mq_open successful
sendQueue();
recvQueue();
return 0;
}
compiled with
gcc -std=gnu99 test.c -lrt -o test
On linux 18.04.3 LTS.
The 3rd argument in mq_receive should be 1024 and not the size of the message sent. According to man page of mq_receive "The msg_len argument specifies the size of the buffer pointed to by msg_ptr; this must be greater than or equal to the mq_msgsize attribute of the queue (see mq_getattr(3))."