为什么我没有看到来自消息队列的消息?

时间:2012-11-17 13:23:57

标签: c unix queue message-queue

我想了解Unix中的消息队列是如何工作的。我写了一个简单的代码,它将一条短消息发送到队列,然后我可以读取该消息。但我的代码显示:

enter image description here

而且我不知道为什么 - 而且我看不到我发送给队列的消息。继承我的代码:

#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;
}

当我使用msgget为此行更改了一行:

int qid = msgget(ftok(".", 0), IPC_CREAT | O_EXCL | 0600);

它显示:

enter image description here

1 个答案:

答案 0 :(得分:1)

来自msgget的文档:

  

msg_perm.mode的低位9位应设置为等于msgflg的低位9位。

您需要为队列添加一些权限,至少是读写。做类似的事情:

int qid = msgget(ftok(".", 0), IPC_CREAT | O_EXCL | 0600);
相关问题