I wrote a simple C program in Linux that uses message queue for IPC (similar to this post). For simplicity mq_send
and mq_receive
are called in the same process.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <mqueue.h>
#define QUEUE_NAME "/test_queue2"
int main(int argc, char **argv)
{
/* initialize the queue attributes */
struct mq_attr attr;
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = 30;
attr.mq_curmsgs = 0;
/* create the message queue */
mqd_t mq = mq_open(QUEUE_NAME, O_CREAT | O_WRONLY, 0644, &attr);
if (mq < 0) {
printf("error in mq_open 1");
exit(1);
}
/* send the message */
int rc = mq_send(mq, "mani123", 8, 0); // need to include the null character too!
if (rc < 0) {
printf("error in mq_send");
exit(1);
}
// ---------------------------------------------------------------
mqd_t mq2 = mq_open(QUEUE_NAME, O_RDONLY);
if (mq2 < 0) {
printf("error in mq_open 2: %s", strerror(errno));
exit(1);
}
char rcvmsg[50];
rc = mq_receive(mq2, rcvmsg, 50, 0);
if (rc < 0) {
printf("error in mq_receive");
exit(1);
}
printf("%s", rcvmsg);
return 0;
}
I am sending/receiving a constant string using the message queue. Now I want to repeat this for a general buffer (array of char). I send the buffer content using mq_send
, but my question is how mq_receive
get the exact size of the sent buffer? Should I send the buffer size separately?