简体   繁体   中英

bad file descriptor while reading posix message queue

Similar threads exist but none of them helped. I am getting bad file descriptor error while reading with below code under linux. I also specify queue attributes when cerating with O_CREAT flag. Any idea? Thanks.

#include <stdio.h>
#include <mqueue.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>


#define Log(...) printf(__VA_ARGS__); fflush(stdout)
int error;

void* producer(void* arg)   {
    Log("producer\n");

    mqd_t q = mq_open("/ytm", O_RDWR);
    mq_send(q, "kardeshians", sizeof("kardeshians"), 1);

}


void* consumer(void* arg)    {

    Log("consumer\n");
    char buff[32];
    mqd_t q = mq_open("/ytm", O_RDONLY);
    int prio;

    while(1)    {
        error =  mq_receive(q,buff,sizeof(buff), NULL);
        if(error)   {
            printf("read error %d  %s\n", errno, strerror(errno));
        }
    }

}



int main()  {

    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 32;
    mqd_t queue = mq_open("/ytm", O_CREAT | O_RDWR, 0, &attr);


    pthread_t tid;
    pthread_create(&tid, 0 , producer, 0);
    pthread_create(&tid, 0 , consumer, 0);


    while(1);
}

Problem was both with the execute permission and message size. After running as a root and making read buffer size bigger than the mq_msgsize it worked. Thanks for error checking suggestions. Here is the working code:

#include <stdio.h>

#include <mqueue.h>
#include <pthread.h>

#include <errno.h>
#include <string.h>


#define Log(...) printf(__VA_ARGS__); fflush(stdout)
int error;

void* producer(void* arg)   {
    Log("producer\n");

    mqd_t q = mq_open("/ytm", O_RDWR);

    if(q == -1)  {
        printf("mq_open error %d  %s\n", errno, strerror(errno));
        exit(0);
    }

   while(1) {
        int retval = mq_send(q, "kardeshians\n", sizeof("kardeshians\n"), 1);

        if(retval == -1)    {
            printf("mq_open error %d  %s\n", errno, strerror(errno));
            exit(0);
        }
   }


}


void* consumer(void* arg)    {

    Log("consumer\n");
    char buff[64];
    mqd_t q = mq_open("/ytm", O_RDONLY);
    int prio;

    while(1)    {
        int retval =  mq_receive(q,buff,sizeof(buff), NULL);
        if(retval ==  -1)   {
            printf("read error %d  %s\n", errno, strerror(errno));
        } else {
            printf("got message : %s", buff);
        }
    }

}



int main()  {

    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 32;
    mq_unlink ("/ytm");
    mqd_t queue = mq_open("/ytm", O_CREAT | O_RDWR, 0, &attr);


    pthread_t tid;
    pthread_create(&tid, 0 , producer, 0);
    pthread_create(&tid, 0 , consumer, 0);


    while(1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM