[英]error: Invalid argument; while sending msgsnd() message; not matching queue ID
[英]Message queue: msgsnd failed : Invalid argument
任何人都可以幫我指出我的程序中的錯誤是什么?
在此先感謝,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個字符)。
我會說很可能會破壞你的類型甚至堆棧上的其他信息(比如msqid
或length
或key
)。
無論這是否是實際問題,它仍然是未定義的行為,應該修復。 我要做的第一件事是檢查替換:
strcpy(buf.mtext, "This is a test message");
有:
strcpy(buf.mtext, "XYZZY"); // 5 plus the NUL
看它是否修復它。
或者,使mtext
足夠大,以存儲您放在那里的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.