Skip to content
Advertisement

Message queue: msgsnd failed : Invalid argument

Can anyone please help me to point out as what is the error in my program?

Thanks in advance, kingsmasher1

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <errno.h>

typedef struct msgbuf {
    long mtype;     /* message type, must be > 0 */
    char mtext[15];  /* message data */
} msgbuf;

int main() {
    key_t key;
    int msqid, pid, length;
    msgbuf buf;

    msqid=msgget(IPC_PRIVATE,IPC_CREAT);

    if(msqid==-1){
        perror("msgget failed");
        return;
    }
    else {
        printf("msgget succeeded. ID:%u",msqid);
    }

    pid=fork();

    if(pid==-1) {
        perror("fork failedn");
    }

    buf.mtype=1;
    strcpy(buf.mtext, "This is a test message");
    length=sizeof(buf.mtext);

    if(msgsnd(msqid,&buf,length,0)!=0) {
        perror("msgsnd failed:n");
    }
    else {
       printf("msgsnd succeededn");
    }
}

Output: msgsnd failed: Invalid argument

Advertisement

Answer

You do not have enough space in your buf.mtext (15 characters) for "This is a test message" (23 characters plust one more for a NUL terminator).

I’d say there’s a good chance that may be corrupting your type or even some other piece of information on the stack (like msqid or length or key).

Whether that’s the actual problem or not, it’s still undefined behaviour and should be fixed. The first thing I’d do is check by replacing:

strcpy(buf.mtext, "This is a test message");

with:

strcpy(buf.mtext, "XYZZY");  // 5 plus the NUL

to see if it fixes it.

Alternatively, make mtext big enough to store the data you’re putting in there.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement