套接字超时:它可以工作,但是为什么以及如何,主要是 select() 函数?

问题描述 投票:0回答:1

这是我现在使用的代码的一部分。

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

我不太清楚 select() 函数是如何工作的,这里的伪代码才是我真正想做的,

    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;

有没有办法实现这个伪代码,这些标志是否存在?

编辑:另外为什么上面代码中的 select 函数中是 sockfd+1 ?为什么要加一个呢?

c sockets timeout posix-select
1个回答
1
投票

阅读手册:

man 2 select

  1. nfds is the highest-numbered file descriptor in any of the three sets, plus 1.
    ,这就是为什么
    sockfd + 1
  2. select()
    返回触发请求事件的描述符数量。只给出一个描述符,所以 select 最多可以返回
    1
  3. 因此,如果在给定的超时时间 3 秒后,没有任何反应,
    select()
    不会返回
    1
    ,因此您认为这是超时。错误情况
    -1
    不予处理。
© www.soinside.com 2019 - 2024. All rights reserved.