简体   繁体   English

从套接字返回的文件描述符大于FD_SETSIZE

[英]File descriptor returned from socket is larger than FD_SETSIZE

I have a problem where the returned file descriptor would gradually increase to be a number larger than FD_SETSIZE . 我有一个问题,其中返回的文件描述符将逐渐增加为大于FD_SETSIZE的数字。

My tcp server is continually shutdown which requires my client to close the socket and reconnect. 我的tcp服务器不断关闭,这需要我的客户端关闭套接字并重新连接。 The client will then attempt to reconnect to the server by calling socket to obtain a new file descriptor before calling connect . 然后,客户端将在调用connect之前通过调用socket尝试重新连接到服务器以获得新的文件描述符。

However it appears that everytime I call socket the file descriptor returned is incremented and after a certain amount of time it becomes larger than FD_SETSIZE , which is a problem where I use select to monitor the socket. 但是,似乎每次调用socket ,返回的文件描述符都会增加,并且经过一定时间后,它变得大于FD_SETSIZE ,这在我使用select监视套接字时是一个问题。

Is it ok to reuse the first file descriptor returned from socket for the connect call even though the the socket was closed? 它是确定重用从返回的第一个文件描述符socketconnect呼叫,即使套接字已关闭? Or is there other workarounds? 还是有其他解决方法?

Reconnect code (looping until connected): 重新连接代码(循环直到连接):

int s = getaddrinfo(hostname, port, &hints, &result);    
if (s != 0) { ... HANDLE ERROR ...}
...
struct addrinfo *rp;
int sfd;
for (rp = result; rp != NULL; rp -> ai_protocol)
{
    sfd = socket( rp->ai_family, rp->ai_sockettype, rp->ai_addrlen);
    if (sfd >= 0)
    {
       int res = connect(sfd, rp->ai_addr, rp->ai_addrlen);
       if (res != -1)
       {
          _sockFd = sfd;
          _connected = true;
          break;   
       }
       else
       {
          close (sfd);
          break; 
       }
    } 
}
if (result != NULL)
{
    free(result);
}

Read Message code: 读取消息代码:

if (_connected)
{
   ...
   retval = select(n, &rec, NULL, NULL, &timeout);
   if (retval == -1) 
   {
      ...
      _connected = false;
      close(_sockFd);      
   }
   else if (retval)
   {
      if (FD_ISSET(_sockFD, &rec) == 0)
      {
         ....
         return;
      }

      int count = read(...)

      if (count)
      {
         ....
         return;
      }
      else
      {
         ....
         _connected = false;
         close(_sockFd);
      } 
   }
}

You're not closing the socket if the connect fails. 如果连接失败,则不会关闭套接字。 So it remains open, occupying an FD, so next time you call socket() you get a new FD. 因此它保持打开状态,占用FD,因此,下次调用socket()时,您将获得一个新的FD。 You're also not breaking out of your loop when connect() succeeds, which is another leak. 当connect()成功时,您也不会脱离循环,这是另一个泄漏。 You're also not checking the result of read() for -1. 您也没有检查-1的read()结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM