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