socket timeout: It works, but why and how, mainly the select() function?

拟墨画扇 提交于 2019-12-11 18:13:33

问题


Here is part of the code I'm using now.

fd_set fdset;
struct timeval tv;
int flags = fcntl(sockfd, F_GETFL);    
fcntl(sockfd, F_SETFL, O_NONBLOCK);

connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));

FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
tv.tv_sec = 3;          
tv.tv_usec = 0;

if (select(sockfd + 1, NULL, &fdset, NULL, &tv) == 1)
{
    int so_error;
    socklen_t len = sizeof so_error;
    getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
    if (so_error == 0) {
        cout << " - CONNECTION ESTABLISHED\n";
    }
} else
{
    cout << " - TIMEOUT\n";
    exit(-1);
}

I don't clearly understand how the select() function works, here in pseudo code is what I really want to do,

    bool showOnce = true;

    connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) 
    while(stillConnecting) /*Some kind of flag of connection status*/
    {
        if(showOnce)
        {
            showOnce = false;
            cout << "Connecting";
        }
    }

    if(connected) /*Another possible flag if it exists*/
        return true;
    else
        return false;

Is there anyway to implement this pseudo code, do these flags exist?

EDIT: Also why is sockfd+1 in the select function in the code above? Why is one added to it?


回答1:


Read the manual: man 2 select:

  1. nfds is the highest-numbered file descriptor in any of the three sets, plus 1., that's why sockfd + 1.
  2. select() returns the number of descriptors which trigger a requested event. Only one descriptor is given, so select can return at most 1.
  3. So if after 3 seconds, the given timeout, nothing happens, select() does not return 1, so you consider it a timeout. The case of an error -1 is not handled.


来源:https://stackoverflow.com/questions/6932512/socket-timeout-it-works-but-why-and-how-mainly-the-select-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!