select()后关闭套接字

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

我正在编写一个 IRC 客户端,我想实现一个“/server”命令来将客户端的连接切换到其他服务器。 在初始化新连接之前,我想关闭套接字的 fd,但 close() 调用失败。有人能告诉我为什么吗? 这是我的代码:

/* Main execution loop */
FD_ZERO(&irc->rdfs);
FD_SET(STDIN_FILENO, &irc->rdfs);
FD_SET(irc->socket_fd, &irc->rdfs);
if ((select(irc->socket_fd + 1, &irc->rdfs, NULL, NULL, NULL)) == -1)
{
  if ((close(irc->socket_fd)) == -1)
    exit(usage(CLOSE_ERROR));
  exit(usage(SELECT_ERROR));
}
if (FD_ISSET(STDIN_FILENO, &irc->rdfs))
{
  fgets(irc->buffer, SIZE - 1, stdin);
  {
    p = strstr(irc->buffer, RET);
    if (p != NULL)
      *p = 0;
    else
      irc->buffer[SIZE - 1] = 0;
  }
  write_on_server(irc, irc->buffer); /* The function where I call switch_server() in */
}
else if (FD_ISSET(irc->socket_fd, &irc->rdfs))
{
  if ((read_on_server(irc)) == 0)
    exit(usage(SERVER_DISCONNECT));
  puts(irc->buffer);
}

这是我试图关闭套接字的 fd 的地方:

void            switch_server(t_irc *irc)
{
if ((close(irc->socket_fd)) == -1) /* This is the close which fail */
    exit(EXIT_FAILURE);
}

void            write_on_server(t_irc *irc, const char * buffer)
{
if (!(strncmp("/server", buffer, strlen("/server"))))
  switch_server(irc);
else
  if ((send(irc->socket_fd, buffer, strlen(buffer), 0)) < 0)
   {
     if ((close(irc->socket_fd)) == -1)
       exit(usage(CLOSE_ERROR));
     exit(usage(CLIENT_SEND_ERROR));
   }
}
c sockets irc posix-select
2个回答
1
投票

如果您想知道为什么像

close()
这样的系统调用失败,请使用
perror()
将错误消息打印到 stderr,或使用
strerror(errno)
将错误代码转换为字符串并以其他方式输出。


1
投票

几乎可以肯定套接字FD是无效的。您需要对此调用 perror(),在 select() 失败时调用

© www.soinside.com 2019 - 2024. All rights reserved.