C++ 消息队列错误的文件描述符错误

C++ 消息队列错误的文件描述符错误,c++,posix,message-queue,C++,Posix,Message Queue,我编写了一个简单的应用程序来理解POSIX消息队列。但该应用程序不断给出“坏文件描述符”错误 感谢stackoverflow用户。我们找到了解决办法。下面是更新的代码 #include <mqueue.h> #include <string.h> #include <iostream> #include <errno.h> using namespace std; int main(int argc, char *argv[]) { m

我编写了一个简单的应用程序来理解POSIX消息队列。但该应用程序不断给出“坏文件描述符”错误

感谢stackoverflow用户。我们找到了解决办法。下面是更新的代码

#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main(int argc,char*argv[])
{
mqd_t消息队列;
mq_attr attr;
messageQueue=mq_open(“/test”,O_RDWR | O_CREAT,0664,&attr);
attr.mq_maxmgs=10;
attr.mq_msgsize=4;
字符c;
int-pid=fork();
//客户
如果(pid==0){
if(mq_receive(messageQueue,&c,1,0)=-1)

cout既然您为
mq\u open
提供了
O\u create
标志和属性列表,那么您应该将
attr.mq\u maxmsg
attr.mq\u msgsize
显式设置为正值。

既然您为
O\u create
标志和
mq\u open
提供了属性列表,那么您应该显式设置
attr.mq\msg
属性mq\u msgsize
为正值。

存在错误,因为接收缓冲区大小不大于mq\u msgsize属性。 只需做两件事,让数组表示char c1[50],而指向它的指针表示char*ptr=c1; 在接收方法中传递此指针,当您打印消息时,打印c1[0]就是它。
还将receive method中的大小更新为50而不是1。

存在错误,因为接收缓冲区大小不大于mq_msgsize属性。 只需做两件事,让数组表示char c1[50],而指向它的指针表示char*ptr=c1; 在接收方法中传递此指针,当您打印消息时,打印c1[0]就是它。
同时将receive method中的大小更新为50而不是1。

检查
mq_open
的返回值以了解它是否工作?@Mat我刚刚尝试过。它不工作。它显示“无效参数”这就是你的问题。阅读手册页,看看它说的关于
EINVAL
的内容。检查
mq_open
的返回值以了解它是否有效如何?@Mat我刚刚尝试过。它不起作用。它说的是“无效参数”好吧,这就是你的问题。阅读手册页,看看它对
EINVAL
@unknown\u user的说明。你完全正确,根据mq\u概览手册,还有一件事消息队列名称应该以斜杠(/)开头@未知用户您完全正确,根据mq\ U概览消息队列名称的手册页,还有一件事应该以斜杠(/)开头