c ++如何使用select查看套接字是否已关闭 [英] c++ how to use select to see if a socket has closed

查看:42
本文介绍了c ++如何使用select查看套接字是否已关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我提供一个如何使用 select() 来查看客户端是否关闭了套接字连接的示例?

Can someone provide me an example of how to use select() to see if a client has closed the connection on a socket?

仅供参考.我用的是 linux.

FYI. I'm using linux.

谢谢!

推荐答案

下面的代码片段首先检查套接字是否被标记为可读(关闭时是这样),然后检查是否真的有任何东西可以读取.

The below snippet first checks if the socket is marked readable (which it is when closed) and then if there's actually anything to be read.

#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ioctl.h>

bool isclosed(int sock) {
  fd_set rfd;
  FD_ZERO(&rfd);
  FD_SET(sock, &rfd);
  timeval tv = { 0 };
  select(sock+1, &rfd, 0, 0, &tv);
  if (!FD_ISSET(sock, &rfd))
    return false;
  int n = 0;
  ioctl(sock, FIONREAD, &n);
  return n == 0;
}

这篇关于c ++如何使用select查看套接字是否已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆