I tried to implement a simple C program using message queues, however the queue doesn't send or receive messages that are longer than 8 characters. I tried to set up all parameters correctly, but I must be missing something.
Below is the code and output.
code:
int main()
{
mqd_t mq = mq_open("/mq", O_RDWR | O_CREAT, 0666, NULL);
if (mq == -1) exit(1);
char* mes = "adventure";
int n = mq_send(mq, mes, sizeof(mes), 0);
char* mes2 = "eightcharacters";
n = mq_send(mq, mes2, sizeof(mes2), 0);
if (n == -1) exit(1);
struct mq_attr attr;
int buflen;
char *buf;
mq_getattr(mq, &attr);
buflen = attr.mq_msgsize;
buf = (char *) malloc(buflen);
printf("buflen: %d\n", buflen);
n = mq_receive(mq, (char *) buf, buflen, NULL);
if (n == -1) { exit(1); }
printf("%s\n",buf);
n = mq_receive(mq, (char *) buf, buflen, NULL);
if (n == -1) { exit(1); }
printf("%s\n",buf);
free(buf);
mq_close(mq);
return 0;
}
output:
buflen: 8192
adventur
eightcha
sizeof
will give you the size of the pointer (you seems to be on a 64bits architecture, so pointers are 8 bytes long).To correct your code:
strlen
function instead ofsizeof
(in that case, you must take care of final\0
)or
char mes2[] = "eightcharacters";