开发者

Message queue: msgsnd failed : Invalid argument

开发者 https://www.devze.com 2023-02-15 18:38 出处:网络
Can anyone please help me to point out as what is the error in my program? Thanks in advance, kingsmasher1

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 failed\n");
    }

    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");
    }
 开发者_如何学JAVA   else {
       printf("msgsnd succeeded\n");
    }
}

Output: msgsnd failed: Invalid argument


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号