Linux 消息队列:msgsnd 失败:参数无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5218238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Message queue: msgsnd failed : Invalid argument
提问by kingsmasher1
Can anyone please help me to point out as what is the error in my program?
谁能帮我指出我的程序中的错误是什么?
Thanks in advance, kingsmasher1
提前致谢,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");
}
}
Output: msgsnd failed: Invalid argument
输出:msgsnd 失败:参数无效
采纳答案by paxdiablo
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).
您的buf.mtext
(15 个字符)中没有足够的空间用于"This is a test message"
(23 个字符加上一个 NUL 终止符)。
I'd say there's a good chance that may be corrupting your type or even some otherpiece of information on the stack (like msqid
or length
or key
).
我会说很有可能会破坏您的类型甚至堆栈上的其他一些信息(例如msqid
orlength
或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.
或者,制作mtext
足够大以存储您放入其中的数据。