我的队列正在发送消息,但没有收到...
任何人都可以帮忙解决这个问题吗?
编者注:改进了代码格式,但需要更多详细信息
<小时/>代码:
#define MAXSIZE 128
void die(char *s)
{
perror(s);
exit(1);
}
struct msgbuf
{
int mtype;
char mtext[MAXSIZE];
};
-> main()
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
struct msgbuf sbuf;
struct msgbuf rcvbuffer;
int buflen;
srand(time(0));
key = rand()%(100+40);
printf("%d",key);
获取给定键的消息队列ID
if ((msqid = msgget(key, msgflg )) < 0) //Get the message queue ID for the given key
die("msgget");
//Message Type
sbuf.mtype = 1;
printf("Enter a message to add to message queue : ");
scanf("%[^\n]",sbuf.mtext);
getchar();
buflen = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
{
printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
die("msgsnd");
}
else
printf("Message Sent\n");
printf("%d",msqid);
exit(0);
if ((msqid = msgget(key, 0666)) < 0)
die("msgget()");
接收消息类型 1 的应答。
//Receive an answer of message type 1.
if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
die("msgrcv");
printf("%s\n", rcvbuffer.mtext);
}
谢谢
最佳答案
我花了一些时间,但我发现了你的错误。消息队列的类型检查取决于 long 类型而不是 int 类型的 mtype 字段。
如果您只是接收消息而不指定类型,那么消息就会通过。但如果您指定类型,则不会,因为“struct msgbuf”中的“mtype”字段是 int 类型而不是 long 类型。 (在我的 - 很可能也是你的 - 架构上,两者之间有 4 个字节的差异)
将 struct msgbuf 中的 mtype 类型更改为 long,它将起作用...
关于c - 代码错误 : message queue not receiving the value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23169516/