为什么没有创建msg队列

问题描述 投票:0回答:1

我正在学习消息队列,编写代码来创建消息队列

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdlib.h>
#include <errno.h>

int main()
{
    key_t key;
    int msgid;

    key = ftok("proj", 64);
    if (key == -1) {
        perror("ftok failed");
        exit(1);
    }
    printf("key:%x\n", key);
    //IPC_CREAT: creating message queue if not exists
    msgid = msgget(key, IPC_CREAT);
    if (msgid == -1) {
        perror("msgget failed");
        printf("errno:%d\n", errno);
        if (errno == ENOENT)
            printf("No message queue exists for key and msgflg did not specify IPC_CREAT\n");
        exit(2);
    }
    printf("msgid:%x\n", msgid);


    return 0;
}

运行该命令未显示输出:ipcs -q

panther2@ubuntu:~/c_codes/msg_queue$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    

如果我犯了任何错误,请你告诉我

linux ipc message-queue
1个回答
1
投票

正如我所看到的,你的代码没有任何问题,但即使在我的系统上,这种行为也很奇怪。

mssget返回0时,一切正常(它应该返回一个0的非负数)并且可以使用队列。

我在你的编程结束时添加了一个for(;;);并再次启动它。 ipcs现在显示:

04025077b 0泥0 0 0

在我ipcrm -q 0并再次启动程序之后,我为每次运行获得了一个新的id。我现在删除了无限循环,并且所有内容仍然有效,每次运行我都有一个不同号码的消息队列,我总是要在下次运行之前销毁它。

真奇怪啊!

我发现了很多关于这个话题的报道,例如:https://www.unix.com/programming/248572-msgget-2-returns-0-workaround-fix.html http://forums.codeguru.com/showthread.php?403036-strange-problem-in-using-msgget%28%29-in-Linux

如果您找到了有效的解决方案,请随时通知我们!

由于我的系统现在在每次运行时生成一个id> 0的新消息队列,我不能再重现这种行为。我不想再重启;)

© www.soinside.com 2019 - 2024. All rights reserved.