消息队列:msgsnd失败:无效的参数

任何人都可以请帮我指出,在我的程序中是什么错误?

在此先感谢,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"); } else { printf("msgsnd succeeded\n"); } } 

输出:msgsnd失败:无效的参数

您的buf.mtext没有足够的空间(15个字符) "This is a test message" (对于NUL终止符,多出23个字符)。

我想说有一个很可能会损坏你的类型,甚至在栈上的其他信息(如msqidlengthkey )。

不管这是不是真正的问题,它仍然是未定义的行为,应该修复。 我要做的第一件事是通过替换来检查:

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

有:

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

看看它是否修复它。

或者,使足够大的mtext来存储你在那里的数据。