【问题标题】:bad file descriptor with close() socket (c++)带有close()套接字的错误文件描述符(c ++)
【发布时间】:2010-04-20 12:12:06
【问题描述】:

当我的程序无法连接另一台主机时,我的文件描述符已用完。 close() 系统调用不起作用,打开的套接字数量增加。我可以用

cat /proc/sys/fs/file-nr

从控制台打印:

连接:没有到主机的路由

关闭:错误的文件描述符

连接:没有到主机的路由

关闭:错误的文件描述符

..

代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <iostream>
using namespace std;

#define PORT            1238
#define MESSAGE         "Yow!!! Are we having fun yet?!?"
#define SERVERHOST      "192.168.9.101"

void
write_to_server (int filedes)
{
  int nbytes;

  nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1);
  if (nbytes < 0)
    {
      perror ("write");
    }
}

void
init_sockaddr (struct sockaddr_in *name,
               const char *hostname,
               uint16_t port)
{
  struct hostent *hostinfo;

  name->sin_family = AF_INET;
  name->sin_port = htons (port);
  hostinfo = gethostbyname (hostname);
  if (hostinfo == NULL)
    {
      fprintf (stderr, "Unknown host %s.\n", hostname);
    }
  name->sin_addr = *(struct in_addr *) hostinfo->h_addr;
}

int main() 
{
 for (;;)
 {
  sleep(1);
  int sock;
  struct sockaddr_in servername;

  /* Create the socket. */
  sock = socket (PF_INET, SOCK_STREAM, 0);
  if (sock < 0)
  {
   perror ("socket (client)");
  }

  /* Connect to the server. */
  init_sockaddr (&servername, SERVERHOST, PORT);
  if (0 > connect (sock,
    (struct sockaddr *) &servername,
    sizeof (servername)))
  {
   perror ("connect");
   sock = -1;
  }

  /* Send data to the server. */
  if (sock > -1)
   write_to_server (sock);
  if (close (sock) != 0)
   perror("close");
 }
return 0;
}

修复:

  if (0 > connect (sock,
    (struct sockaddr *) &servername,
    sizeof (servername)))
  {
   perror ("connect");
  }

  else
   write_to_server (sock);

  if (close (sock) != 0)
   perror("close");

【问题讨论】:

    标签: c++ sockets file-descriptor


    【解决方案1】:

    看来问题出在程序的结构上。每次通过无限循环,您都在创建一个新套接字。我建议将其移出循环并重新使用它。

    如果您只想修复您现在的操作方式,请在您现在拥有的“连接”失败 if 语句中使用 close。描述符由“socket”调用分配,并且只与“connect”调用连接。通过将“sock”变量设置为-1,您将丢弃“socket”分配的描述符。调用close,然后将它设置为-1,你应该被设置。

    【讨论】:

    • +1:即使连接失败,你仍然需要关闭套接字而不是扔掉句柄。
    猜你喜欢
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多