posix mqueue中的错误文件描述符

时间:2014-12-12 13:15:37

标签: c posix file-descriptor mqueue

任何人都可以帮我解决posix mqueue中的错误文件描述符问题。我正在尝试读取RAW套接字数据包并将它们置于mqueue中。

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<mqueue.h>
#include<netinet/ip_icmp.h>   
#include<netinet/udp.h> 
#include<netinet/tcp.h>  
#include<netinet/ip.h>
#include<netinet/if_ether.h>
#include<net/ethernet.h>

#define QUEUE_NAME  "/test_queue"
#define MAX_SIZE    71680



#define CHECK(x) \
    do { \
        if (!(x)) { \
            fprintf(stderr, "%s:%d: ", __func__, __LINE__); \
            perror(#x); \
            exit(-1); \
        } \
    } while (0) \


int main(int argc, char **argv)
{
    mqd_t mq;
    struct mq_attr attr;
    char buff[MAX_SIZE + 1];
    unsigned char* buffer = (unsigned char*) malloc(sizeof(65536));
    int saddr_size , data_size,sock_raw;
    struct sockaddr saddr;

    /* initialize the queue attributes */
    attr.mq_flags = 0;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = MAX_SIZE;
    attr.mq_curmsgs = 0;

    /* create the message queue */
    mq = mq_open(QUEUE_NAME, O_CREAT | O_RDONLY, 0644, &attr);
    CHECK((mqd_t)-1 != mq);

    sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;
    if(sock_raw < 0)
    {
       perror("Socket Error\n");
       return 1;
    }
    saddr_size = sizeof saddr;
    data_size = recvfrom(sock_raw , buffer ,65536 , 0 , &saddr , (socklen_t*)&saddr_size);

    if(data_size <0 )
    {
       printf("Recvfrom error , failed to get packets\n");
       return 1;
    }

    memcpy(buff,buffer,65536);


    CHECK(0 <= mq_send(mq, buffer, MAX_SIZE, 0));

    printf("Msg sent");

    CHECK((mqd_t)-1 != mq_close(mq));

    return 0;
}

我得到的输出是

main:64:0&lt; = mq_send(mq,buffer,MAX_SIZE,0):错误的文件描述符

1 个答案:

答案 0 :(得分:3)

您正在尝试将(mq_send)写入以只读方式打开的消息队列描述符(O_RDONLY)。

oflags 参数更改为O_CREAT | O_RDWR,发送将有效。

Linux手册页并没有调用它,但是others do:EBADF可能意味着fd或fd类句柄完全无效,或者它对于请求的操作无效。