Home > Enterprise >  C message queue is read only if given type is 0
C message queue is read only if given type is 0

Time:01-03

I created 2 functions that read from a given message queue a given type, at first it worked but then in only began reading messages if sent with type equal to 0, these are the functions:

int sendMessage(int msgQId,int tipo, char *msg) {
    my_msg_buf msgBuf;
    msgBuf.tipo = tipo;
    char *str;
    strncpy(msgBuf.testo, msg,MAX_LINE_LENGTH-1);
    /* Mando messaggio specificato */
    if (msgsnd(msgQId, (void *)&msgBuf, MAX_LINE_LENGTH, 0) == -1) {
        fprintf(stderr, "Error sending message: %s\n", strerror(errno));
        return -1;
    }
    
    str= receiveMessage(msgQId,tipo);
    printf("Mess: %s\n",str);
    
    printf("Message sent\n");
    return 0;
}

char *receiveMessage(int msgQId, int tipo) {
    my_msg_buf msgBuf;
    /* Receive message by type */
    if (msgrcv(msgQId, (void *)&msgBuf, MAX_LINE_LENGTH, tipo, IPC_NOWAIT) == -1) {
        if(errno != ENOMSG)
            fprintf(stderr, "Error: %s\n", strerror(errno));
        return NULL;
    }

    return strdup(msgBuf.testo);
}

The strucuture I am using is this:

typedef struct mymsgbuf {
    int     tipo;
    char    testo[MAX_LINE_LENGTH];
} my_msg_buf;

Where MAX_LINE_LENGTH is 256

The functions are used elsewhere in the project, the str variable using the read function is only there for testing. When calling receiveMessage with tipo it gives back NULL, when putting 0 in place of the tipo variable it gives the message back. I even tried putting sleeps in the middle but nothing seems to work. Can you give a hand please? Thanks.

CodePudding user response:

The Linux manual page for msgsnd and msgrcv says that the mesage type field (the first member of the message structure) is a long.

On a normal 64-bit Linux system int is 32 bits, while long is 64 bits. That mismatch in type leads to undefined behavior.

The manual page also states that the message id needs to be larger than zero.

So your tipo field needs to be using the type long, and it must always be larger than 0.

  • Related