C mqueue doesn't send or receive the entire message

475 views Asked by At

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
2

There are 2 answers

0
Mathieu On BEST ANSWER

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:

  • use strlen function instead of sizeof (in that case, you must take care of final \0)

or

  • replace your string declaration:

char mes2[] = "eightcharacters";

0
Andrew Henle On

Given the code

char* mes = "adventure";
int n = mq_send(mq, mes, sizeof(mes), 0);

sizeof(mes) is the size of the pointer mes, not the length of the string it points to.