消息队列 mq 发送错误。错误的文件描述符

Message queque mq send error. Bad file descriptor

我正在尝试写入我的消息队列 (mq_send)。

这是我先打开队列然后写入队列的代码。

开幕式:

int MQconnect (mqd_t * mq, char * name)
{
    //printf("hello from MQconnect\n");
    do{
        mq=mq_open(name, O_WRONLY);  //O_RDONLY
    }while(mq==-1);

    if(mq== -1){
        return 0;
    }
    else
        return 1;
    // Connects to an existing mailslot for writing Uses mq as reference pointer, so that you can     reach the handle from anywhere/
    // Should return 1 on success and 0 on fail*/
}

写作:

int MQwrite (mqd_t mq, void * sendBuffer) // (const char) sendBuffer
{
    int nrOfBytes = mq_send(mq, (const char)sendBuffer, 1024, 10);

    printf("\n%d", nrOfBytes);

    return nrOfBytes; //nrOfBytes;

    // Write a msg to a mailslot, return nr Uses mq as reference pointer, so that you can reach the handle from anywhere
    // should return number of bytes read         */
}

打开工作正常,但我无法写入消息队列。

mq_send return -1 作为 return 值,错误消息为:

errno 的值:9 perror 打印的错误:错误的文件描述符 错误:错误的文件描述符

从这个函数调用上述函数:

void * mqClient(void * arg){
    pthread_mutex_lock(&mutex);

    char answer[20];
    mqd_t mq_on_server;
    usleep(1000);
    int response = MQconnect(&mq_on_server, "/servermq");
    if(response==0){
        printf("something went wrong with MQconnect\n");
    }
    else{
        //This loop continously scans planets given by the user
        //while(!(0)){
    printf("\nWrite to mailbox: ");
    scanf("%s", answer);


    MQwrite (mq_on_server, &answer);
    int c;
    while ( (c = getchar()) != '\n' && c != EOF);
    //fflush(stdout);
        //}

    }

    pthread_mutex_unlock(&mutex);
}

有人知道我为什么会收到这种错误吗?我的朋友有完全相同的代码并且对他有效。

您忘记取消引用 MQconnect 中给定的指针。

int MQconnect (mqd_t * mq, char * name)
{
    //printf("hello from MQconnect\n");
#if 0
    /* wrong part */
    do{
        mq=mq_open(name, O_WRONLY);  //O_RDONLY
    }while(mq==-1);

    if(mq== -1){
#else
    /* fixed code */
    do{
        *mq=mq_open(name, O_WRONLY);  //O_RDONLY
    }while(*mq==-1);

    if(*mq== -1){
#endif
        return 0;
    }
    else
        return 1;
    // Connects to an existing mailslot for writing Uses mq as reference pointer, so that you can     reach the handle from anywhere/
    // Should return 1 on success and 0 on fail*/
}