读取套接字:EAGAIN:资源暂时不可用

时间:2012-04-25 14:51:50

标签: c++ sockets

我用C ++创建了一个套接字,我需要它才能有一定的连接超时。这就是发生的事情:

  • 创建套接字
  • 将其设为NON_BLOCKING
  • 致电连接
  • 按预期返回-1和errno EINPROGRESS
  • 致电选择
  • 返回> 0,因此已建立连接
  • 再次插座BLOCKING

此部分的代码如下:

bool mastControl::prepareSocket(char * address, int port, int * sockfd) {

    struct sockaddr_in serv_addr;
    struct timeval timeout = {0,100000};
    struct timeval connTimeout;
    struct hostent * server = NULL;
    fd_set socketSet;
    socklen_t lon;
    int sockOpt = 0;
    long socketFlags = 0;
    int buffersize = 8;
    int res = 0;
    int connectReturn = 0;
    const int WAIT_TO_RECONN = 15;

    server = gethostbyname(address);
    *sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if (*sockfd < 0) {
        qDebug()<<"Impossible to open socket: "<<strerror(errno);
        return false;
    }

    if (server == NULL) {
        qDebug()<<"No such host: "<<strerror(h_errno);
        return false;
    }

    // Initializating server direction struct:
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
          (char *)&serv_addr.sin_addr.s_addr,
          server->h_length);
    serv_addr.sin_port = htons(port);

    // Making socked non-blocking in order to set a timeout value for connection:
    if((socketFlags = fcntl(*sockfd, F_GETFL, NULL)) < 0){
        qDebug()<<"Impossible to retrieve sockets descriptor flags "<<strerror(errno);
        return false;
    }
    socketFlags |= O_NONBLOCK;
    if(fcntl(*sockfd, F_SETFL, socketFlags) <0){
        qDebug()<<"Impossible to update sockets descriptor flags: "<<strerror(errno);
        return false;
    }

    connectReturn = connect(*sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr));
    if(connectReturn < 0){
        if(errno == EINPROGRESS){
            do{
                // Establishing a 15 seconds timeout:
                connTimeout.tv_sec = 15;
                connTimeout.tv_usec = 0;
                FD_ZERO(&socketSet);    // Initialising set of sockets as an empty set
                FD_SET(*sockfd, &socketSet);    // Adding socket to set
                connectReturn = select(*sockfd+1, NULL, &socketSet, NULL, &connTimeout);
                if(connectReturn<0 && errno!=EINTR){ // Error in select
                    qDebug()<<"Connection error in select function: "<<strerror(errno);
                    return false;
                }
                else if(connectReturn>0){ // Socket selected for writing
                    lon = sizeof(int);
                    if(getsockopt(*sockfd, SOL_SOCKET, SO_ERROR, (void*)(&sockOpt), &lon) <0){
                        qDebug()<<"Unnable to get socket options: "<<strerror(errno);
                        return false;
                    }
                    // Checking the value returned:
                    if(sockOpt){
                        qDebug()<<"Error in delayed connection: "<<strerror(errno);
                        return false;
                    }
                    break;
                }
                else{ // Timeout
                    qDebug()<<"Connection timeout exceeded: "<<strerror(errno);
                    return false;
                }
            } while (1);
        }
        else{
            qDebug()<<"Connection error: "<<strerror(errno);
            sleep(WAIT_TO_RECONN); // Wait 15 seconds
            return false;
        }
    }

    //Connected

    // Must set the socket as blocking again:
    if((socketFlags = fcntl(*sockfd, F_GETFL, NULL)) < 0){
        qDebug()<<"Impossible to retrieve sockets descriptor flags "<<strerror(errno);
        return false;
    }
    socketFlags &= (~O_NONBLOCK);
    if(fcntl(*sockfd, F_SETFL, socketFlags) <0){
        qDebug()<<"Impossible to update sockets descriptor flags "<<strerror(errno);
        return false;
    }

    if (setsockopt (*sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                    sizeof(timeout)) < 0) {
        qDebug()<< "ERR  - setsockopt failed";
        return false;
    }

    if (setsockopt (*sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                    sizeof(timeout)) < 0) {
        qDebug()<< "ERR  - setsockopt failed";
        return false;
    }
    if ((res = setsockopt (*sockfd, SOL_SOCKET, SO_SNDBUF, &buffersize,
                           sizeof(buffersize))) == -1) {
        qDebug()<< "ERR  - setsockopt failed (SO_SNDBUF) = " << res;
        return false;
    }
    //Socket Ready

    return true;
}

这没关系。但后来我有一个循环,我正在调用一个函数来检查是否收到了一个新的数据包来读取:

bool mastControl::findPacket(int sockfd, st_messageMastToPc * messageReceived, bool * connected) {

    int n = 0;
    bool messageFound = false;
    char * buffer = (char *) messageReceived;
    unsigned int pos = 0;

    while ( ((n = read(sockfd, &(buffer[pos]), 1)) > 0) and not messageFound) {

        //qDebug()  << "read output " << n;
        if (n == 1) {
            pos++;

            if ( (pos == 1) && (buffer[0] == 2)) {
                // Some stuff...
            } else if ( (pos == 2) && (buffer[1] == 2) ) {
                // Some stuff...
            } else if (pos >= uiMessageMastToPcSize) {
                messageFound = true;
                //Complete message received
            } else if (pos < 2) {
                // Reseting pos
                pos = 0;
            }
        }
    }

    if (n < 0){
        qDebug()<< "Disconnected. Reason #" << errno << ": " << strerror(errno);
        *connected = false;
    }

    return messageFound;
}

读取功能将EAGAIN设为errno,这意味着“资源暂时不可用”。然后我假设我已断开连接,并且由于布尔连接现在为假,在循环中我将尝试重新连接再次创建套接字,等等。

所以,首先我不知道为什么我收到这个错误。

第二,我不知道我是否完全断开连接,或者是在发生此错误后创建新套接字时断开连接的人。

任何帮助?

1 个答案:

答案 0 :(得分:12)

EAGAIN并不意味着您已断开连接,只是意味着“现在没有什么可读的;请稍后再试”。

你可以用fcntl(2)取消O_NONBLOCK(让read等待,直到有可用的东西),或者在调用{select(2)之前等待套接字{{3}}。 1}}。

编辑:既然您已经添加了更多代码,我可以看到您正在为套接字设置read。这可能会导致阻止SO_RCVTIMEO返回read(因此,如果您不希望发生这种情况,只需单独留下EAGAIN)。