À l'aide de select() pour les sockets non bloquant pour se connecter retourne toujours 1

Cette question est très similaire (ou presque identique) à Non blocage socket de connexion, sélectionnez() retourne toujours 1; cependant, je n'arrive pas à trouver où mon code est en perte de vitesse.

Je suis en utilisant les sockets non bloquant et que vous voulez utiliser select() lors de la connexion d'un client à un serveur pour vérifier timeout/succès. Le problème est de sélectionner() retourne toujours 1 presque immédiatement, même quand je n'ai même pas le serveur en cours d'exécution et il n'y a rien à se connecter. Merci d'avance pour l'aide, extrait de code est comme suit:

//Loop through the addrinfo structs and try to connect to the first one we can
for(p = serverinfo; p != NULL; p = p->ai_next) {
    if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) 
    {
        //We couldn't create the socket, try again
        perror("client: socket");
        continue;
    }

    //Set the socket to non-blocking
    int flags = fcntl(sockfd, F_GETFL, 0);
    fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);

    if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
        //The error was something other than non-block/in progress, try next addrinfo
        if(errno != EINPROGRESS) 
        {
            close(sockfd);
            perror("client: connect");
            continue;
        }

        fd_set write_fds;
        FD_ZERO(&write_fds);            //Zero out the file descriptor set
        FD_SET(sockfd, &write_fds);     //Set the current socket file descriptor into the set

        //We are going to use select to wait for the socket to connect
        struct timeval tv;              //Time value struct declaration
        tv.tv_sec = 5;                  //The second portion of the struct
        tv.tv_usec = 0;                 //The microsecond portion of the struct

        //DEBUG: This is ALWAYS 1
        int select_ret = select(sockfd + 1, NULL, &write_fds, NULL, &tv);
        cout << select_ret << endl;

        //Check return, -1 is error, 0 is timeout
        if(select_ret == -1 || select_ret == 0)
        {
            //We had an error connecting
            cout << "Error Connecting\n";
            close(sockfd);
            continue;
        }
    }

    //We successfully connected, break out of loop
    break;
}
Thos est presque une copie de stackoverflow.com/questions/8417821/...

OriginalL'auteur Darren Swanson | 2012-07-01