C 为什么我看不到消息队列中的消息?
我想了解Unix中的消息队列是如何工作的。我写了一个简单的代码,它向队列发送一条短消息,然后我就可以阅读该消息了。但我的代码显示: 我不知道为什么——我看不到我发送给队列的消息。这是我的密码:C 为什么我看不到消息队列中的消息?,c,unix,queue,message-queue,C,Unix,Queue,Message Queue,我想了解Unix中的消息队列是如何工作的。我写了一个简单的代码,它向队列发送一条短消息,然后我就可以阅读该消息了。但我的代码显示: 我不知道为什么——我看不到我发送给队列的消息。这是我的密码: #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> #include <unist
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
struct mymsgbuf {
long mtype;
char mtext[1024];
}msg;
int send_message(int qid, struct mymsgbuf *buffer )
{
int result = -1, length = 0;
length = sizeof(struct mymsgbuf) - sizeof(long);
if((result = msgsnd(qid, buffer, length, 0)) == -1)
return -1;
return result;
}
int read_message(int qid, long type, struct mymsgbuf *buffer)
{
int result, length;
length = sizeof(struct mymsgbuf) - sizeof(long);
if((result = msgrcv(qid, buffer, length, type, 0)) == -1)
return -1;
printf("Type: %ld Text: %s\n", buffer->mtype, buffer->mtext);
return result;
}
int main(int argc, char **argv)
{
int buffsize = 1024;
int qid = msgget(ftok(".", 0), IPC_CREAT | O_EXCL);
if (qid == -1)
{
perror("msgget");
exit(1);
}
msg.mtype = 1;
strcpy(msg.mtext, "my simple msg");
if((send_message(qid, &msg)) == -1)
{
perror("msgsnd");
exit(1);
}
if((read_message(qid, 1, &msg) == -1))
{
perror("msgrcv");
exit(1);
}
return 0;
}
它表明:
来自以下文档: msg_perm.mode的低阶9位应设置为等于msgflg的低阶9位 您需要向队列中添加一些权限,至少是读写权限。做一些类似于:
int qid = msgget(ftok(".", 0), IPC_CREAT | O_EXCL | 0600);
请确保在重新运行应用程序之前删除现有队列(
ipcs-q
to list,ipcrm-q
to clean)不幸的是,相同的结果是:(-msgget:Permission denided您使用的是什么操作系统?请确保删除该队列。如果您曾经以其他用户(特别是root用户)的身份运行过该代码),您可能没有删除正确的队列。我使用Kubuntu 12.04 LTS。我从未以root用户身份运行过此代码,就像我自己一样。当我删除队列时(没有队列,我确定,已选中它)再次运行我的代码,得到消息msgget:Permission denided
这很奇怪,应该可以,对吧?是的,在Linux上对我有效。尝试更改第一个ftok
参数(例如,更改为/tmp
)。
int qid = msgget(ftok(".", 0), IPC_CREAT | O_EXCL | 0600);