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

查看:1311
本文介绍了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?

FYI。我正在使用linux。

FYI. I'm using linux.

谢谢!

推荐答案

snippet首先检查套接字是否被标记为可读(这是关闭时),然后如果实际上有任何要读的东西。

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天全站免登陆