2

I am trying to use poll because my previous usage of select() was failing due to having more than 1024 file descriptors monitored in a single process. My program has to simultaneously check thousands of ip addresses and ports using connect() . It is a kind a of inquiry to know that host is healthy or not . I put each inquiry in a different thread. Here is my function

int connect_nonb(struct sockaddr_in sa , int sock, int timeout)
{
    int flags = 0, error = 0, ret = 0;
    socklen_t   len = sizeof(error);
    struct timeval  t_struct;
struct pollfd pfd;
pfd.fd = sock;
pfd.events = POLLERR|POLLOUT;
pfd.revents = 0;
//set socket nonblocking flag
    if( (flags = fcntl(sock, F_GETFL, 0)) < 0)
            return -11;

    if(fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
            return -12;

    //initiate non-blocking connect
    if( (ret = connect(sock, (struct sockaddr *)&sa, sizeof(rtinetaddr_tp))) < 0 ){
            if (errno != EINPROGRESS)
    {   
        return errno;
    }
}
    if(ret == 0){    //then connect succeeded right away
        goto done;
    }
    //we are waiting for connect to complete now
    if( (ret = poll(&pfd, 1,timeout)) < 0){
return -1;
}
    if(ret == 0){   //we had a timeout
 errno = ETIMEDOUT;
    return errno;
    }

    if(ret > 0){
        if(getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0){
    return errno;
    }
    }

    if(error){  //check if we had a socket error
        errno = error;
    return errno;
    }

done:
    if(fcntl(sock, F_SETFL, flags) < 0){
            return -1;
}

My only objective is to reduce default time out for connect and the same above function is behaving correctly in that regard.

But in some examples I have seen, poll is used in an infinite loop . Should I also use an infinite loop? FYI I am checking these connections per thread . I found a good refrence here

Duck
  • 26,924
  • 5
  • 64
  • 92
Akaks
  • 461
  • 3
  • 21
  • 2
    One tend to put the `poll` in an infinite loop if one is doing more in that loop, for example if it's ones main event/processing loop. – Some programmer dude Apr 14 '14 at 15:49
  • 2
    Also, after the `poll` call, you should see what events was returned. For example, you should not check the error unless `POLLERR` is set in `revents`. – Some programmer dude Apr 14 '14 at 15:51
  • @JoachimPileborg +1 thanks for comments . I am not doing other operations there . Main focus was justproper timeout. – Akaks Apr 14 '14 at 16:33

1 Answers1

0

Yes, you need to loop calls to poll(2) (or to select(2) if you used it). This answer explains in detail why (and how)....

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Thanks a lot for answer . So what if I will use my above function in a separate thread for each connect test ? – Akaks Apr 14 '14 at 18:57