我第一次使用poll(),是否需要无限循环?

时间:2014-04-14 15:44:14

标签: c linux sockets networking

我正在尝试使用poll,因为我之前使用的select()由于在一个进程中监控了超过1024个文件描述符而失败了。我的程序必须使用connect()同时检查数千个IP地址和端口。知道主人是否健康是一种询问。我将每个查询放在一个不同的主题中。这是我的功能

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;
}

我唯一的目标是减少连接的默认超时时间,相同的上述功能在这方面表现正常。

但在我看到的一些例子中,poll用于无限循环。我还应该使用无限循环吗?仅供参考我正在检查每个线程的这些连接。我找到了一个很好的参考here

1 个答案:

答案 0 :(得分:0)

是的,你需要循环调用poll(2)(如果你使用的话,还是select(2))。 This answer详细解释了为什么(以及如何)......

相关问题