C:无法打开消息队列

时间:2017-12-23 16:26:41

标签: c message-queue

我正在开发OpenSuse 42.3 Leap。这是我第一次接触Unix消息队列,我在打开新队列时遇到了一些基本问题。我最初的问题是我无法打开两个队列,但经过几次尝试后我将问题简化为这种奇怪的行为:

如果我编译并运行此

#include<stdio.h>
#include <mqueue.h>

int main() {

//    printf("Hello world!\n");

/* create queue */
char *q_name = "/myQueue";
mqd_t desc = mq_open(q_name, O_RDWR | O_CREAT);
if(desc == (mqd_t) -1)
    perror("Error in mq_open");
printf("We have opened %d\n", desc);

/* close descriptor and unlink name */
if (mq_close(desc)) perror("Error in close:");
if (mq_unlink(q_name)) perror("Error in unlink:");

return 0;
}

它适用于标准输出:

We have opened 3

队列正确关闭,我可以重新运行它,没有错误。

但如果我取消注释该行

printf("Hello world!\n");

它显然仍然正确编译,但在运行时输出

Hello world!
Error in mq_open: Invalid argument
We have opened -1
Error in close:: Bad file descriptor
Error in unlink:: No such file or directory

如果不是简单的'Hello world!我试着打印:

printf("Hello world! My pid = %d\n", getpid());

然后代替Invalid argument错误

Error in mq_open: Bad address

生产。

知道为什么这个简单的printf会导致队列崩溃吗?

1 个答案:

答案 0 :(得分:1)

从mq_open手册页:

  

如果在oflag中指定了O_CREAT,那么必须有两个额外的参数   提供。 [...]

您不提供它们,因此您有未定义的行为。似乎发生的事情是,缺少的参数是从内存中的某个地方获取的,并且根据您之前的程序执行的操作会发生什么不同。