消息队列错误文件描述符错误
问题描述:
我编写了一个简单的应用程序来理解POSIX消息队列。但该应用程序不断给“错误的文件描述符”错误。消息队列错误文件描述符错误
感谢*用户。我们找到解决方案。以下是更新的代码。
#include <mqueue.h>
#include <string.h>
#include <iostream>
#include <errno.h>
using namespace std;
int main(int argc, char *argv[])
{
mqd_t messageQueue;
mq_attr attr;
messageQueue = mq_open("/test",O_RDWR|O_CREAT,0664,&attr);
attr.mq_maxmgs = 10;
attr.mq_msgsize = 4;
char c;
int pid = fork();
//client
if(pid == 0) {
if(mq_receive(messageQueue,&c,1,0) == -1)
cout<<"Error:"<<strerror(errno)<<"\n";
cout<<"Received:"<<c<<"\n";
}
//server
else if(pid > 0) {
c = 'a';
if(mq_send(messageQueue,&c,1,0) == -1)
cout<<"Error:"<<strerror(errno)<<"\n";
cout<<"Send:"<<c<<"\n";
mq_close(messageQueue);
}
else {
cout<<"Fork error\n";
}
return 0;
}
答
既然你提供O_CREAT
标记和属性列表mq_open
,你应该明确地设置attr.mq_maxmsg
和attr.mq_msgsize
为正值。
+0
@unknown_user你是绝对正确的,根据mq_overview消息队列名称的手册页,还应该以斜杠(/)开头, – onurozcelik 2012-03-27 08:53:55
答
错误存在,因为接收缓冲区大小不大于mq_msgsize属性。 只是做了两件事使数组说char c1 [50]和一个指向它的指针说char * ptr = c1; 通过这个指针在接收方法和当你打印消息打印c1 [0]就是它。 同时更新接收方法的大小为50而不是1.
检查'mq_open'的返回值以了解它是否有效? – Mat 2012-03-27 08:04:30
@Mat我刚试过。它不工作。它说“无效的参数” – onurozcelik 2012-03-27 08:11:17
那是你的问题。阅读手册页,看看它说'EINVAL'。 – Mat 2012-03-27 08:12:12