onurozcelik
onurozcelik

Reputation: 1214

Message queue bad file descriptor error

I write a simple application to understand POSIX message queues. But the app continuously gives "Bad file descriptor" error.

Thanks to stackoverflow users. We find the solution. Below is the updated code.

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

Upvotes: 1

Views: 5942

Answers (2)

Amit
Amit

Reputation: 1

error exist because the receiving buffer size is not greater than mq_msgsize attribute. just do two things make an array say char c1[50] and a pointer to it say char *ptr=c1; pass this pointer in receive method and when u print message print c1[0] that's it. Also update the size in receive method to 50 and not 1.

Upvotes: 0

xaero99
xaero99

Reputation: 327

Since you provide O_CREAT flag and an attribute list to mq_open, you should explicitly set attr.mq_maxmsg and attr.mq_msgsize to a positive value.

Upvotes: 1

Related Questions