高级IO之Select_pselect_poll_epoll(四)

select() 模型3大常见陷阱:从FD_SETSIZE限制到EINTR信号处理 本文深入剖析select()函数在网络编程中的三大常见陷阱:FD_SETSIZE的文件描述符数量限制、fd_set被内核修改的特性,以及EINTR信号中断处理。通过实际代码示例和解决方案,帮助开发者避免这些潜在问题,构建更健壮的网络应用。特别针对FD_SET等关键操作提供了优化建议和最佳实践。 阅读详情

1. 基础概念

同时操作多个fd时,如果使用阻塞的方式,可能导致程序效率低下。我们可以使用非阻塞方式的IO,通过不断查询数据操作的结果来进行接下来的操作,这种处理方式就是轮询,缺点就是非常消耗CPU资源。所以在某种意义上其相当于阻塞的调用了IO函数read或者write,可以通过异步IO的方式来解决这个问题,但是因为一个进程只使用一个或者几个信号,当捕获该信号时无法判断是哪个fd数据就绪。最好的方式就是使用IO mutiplexing,虽然该系列函数是阻塞同步的,但是因为能够筛选一个范围中的fd,所以效率也高很多。

2. 主要API

2.1 select/pselect
#include <sys/select.h>
int select(int maxfdp1, fd_set *restrict readfds, fd_set *restrict writefds, fd_set *restrict exceptfds, struct timeval *restrict tvptr);
Returns: count of ready descriptors, 0 on timeout, −1 on error


int pselect(int maxfdp1, fd_set *restrict readfds, fd_set *restrict writefds, fd_set *restrict exceptfds, const struct timespec *restrict tsptr, const sigset_t *restrict sigmask);
Returns: count of ready descriptors, 0 on timeout, −1 on error

int FD_ISSET(int fd, fd_set *fdset);
Returns: nonzero if fd is in set, 0 otherwise
void FD_CLR(int fd, fd_set *fdset);
void FD_SET(int fd, fd_set *fdset);
void FD_ZERO(fd_set *fdset);

tvptr为NULL时,select函数阻塞等待直到有fd就绪或者被信号打断;当其值为0时,select函数非阻塞,其特征为非阻塞同步;当其值大于0时,select函数阻塞等待直到有fd就绪或者该参数指定的时间到期。linux中如果该函数在到期时间内返回,会以剩余时间更新tvptr的值。
  readfds,writefds,exceptfds参数指定了需要“捕捉”的fd。使用FD_XXX系列函数对该三个fd_set进行操作。如果这三个参数都为NULL,该函数相当于sleep。maxfdp1应为最大的fd+1,避免内核查询这三个fd_set中其他不相关的位置。具体三个fd_set的布局如下图所示:
这里写图片描述
  select函数返回值可能有三种情况:

  • A return value of −1 means that an error occurred. In this case, none of the descriptor sets will be modified.
  • A return value of 0 means that no descriptors are ready. When this happens, all the descriptor sets will be zeroed out.
  • A positive return value specifies the number of descriptors that are ready. if the same descriptor is ready to be read and written, it will be counted twice in the return value. The only bits left on in the three descriptor sets are the bits corresponding to the descriptors that are ready.

pselect与select类似,其提供更高精度的时间参数且该参数在该函数返回时不会更改。sigmask参数用来屏蔽信号,等该函数返回时,恢复调用该函数前的sigmask值。
  特别的,理解fd就绪的真正含义:

  • A descriptor in the read set (readfds) is considered ready if a read from that descriptor won’t block.
  • A descriptor in the write set (writefds) is considered ready if a write to that
    descriptor won’t block.
  • A descriptor in the exception set (exceptfds) is considered ready if an exception condition is pending on that descriptor.

NOTE : File descriptors for regular files always return ready for reading, writing, and exception conditions. It is important to realize that whether a descriptor is blocking or not doesn’t affect whether select blocks. If we encounter the end of file on a descriptor, that descriptor is considered readable by select. We then call read and it returns 0.

以上注意事项需要重点理解下:一般常规文件都不会阻塞读写函数。select是否阻塞是由tvptr决定,而和fd是否阻塞没有关系。如果遇到文件末尾的时候,select会认为其是可读的,此时调用read函数返回0。

2.2 poll
#include <poll.h>
int poll(struct pollfd fdarray[], nfds_t nfds, int timeout);
Returns: count of ready descriptors, 0 on timeout, −1 on error
//以下是man page的描述:
//On success, a positive number is returned; this is the number of structures which have nonzero revents fields
//个人觉得这个描述会更好,因为不一定一个事件就代表了一个fd。

struct pollfd {
int fd; /* file descriptor to check, or <0 to ignore */
short events; /* events of interest on fd */
short revents; /* events that occurred on fd */
};

poll与select函数类似,但是编程接口不同。fdarray数组每个成员存储我们该兴趣的fd及相应的事件,revents在该函数返回时相应的event参数中的位被置位,来反映哪个事件发生,nfds指定该数组的成员数。timeout可以取三个值:

  • timeout == −1
    We return when one of the specified descriptors is ready or when a signal is caught. If a signal is caught, poll returns −1 with errno set to EINTR
  • timeout == 0
    Don’t wait. All the specified descriptors are tested, and we return immediately. This is a way to poll the system to find out the status of multiple descriptors, without blocking in the call to poll.
  • timeout > 0
    Wait timeout milliseconds. We return when one of the specified descriptors is ready or when the timeout expires. If the timeout expires before any of the descriptors is ready, the return value is 0.

这里写图片描述

>**NOTE:When a descriptor is hung up (POLLHUP), we can no longer write to the descriptor. There may, however, still be data to be read from the descriptor.**
2.3 epoll
#include <sys/epoll.h>
int epoll_create(int size);int epoll_create1(int flags);
Returns:On success, a nonnegative file descriptor. On error, -1 is returned, and errno is set to indicate the error.

int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
Returns:When successful, returns zero. When an error occurs, returns -1 and errno is set appropriately.

int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
int epoll_pwait(int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t *sigmask);
Returns: When successful, returns the number of file descriptors ready for the requested I/O, or zero if no file descriptor became ready during the requested timeout milliseconds. When an error occurs, returns -1 and errno is set appropriately.

typedef union epoll_data {
    void        *ptr;
    int          fd;
    uint32_t     u32;
    uint64_t     u64;
} epoll_data_t;

struct epoll_event {
    uint32_t     events;      /* Epoll events */
    epoll_data_t data;        /* User data variable */
};

以下引用来自MAN Page:

  • Epoll_create() creates an epoll(7) instance. Since Linux 2.6.8, the size argument is ignored, but must be greater than zero; epoll_create() returns a file descriptor referring to the new epoll instance. This file descriptor is used for all the subsequent calls to the epoll interface. When no longer required, the file descriptor returned by epoll_create() should be closed by using close. When all file descriptors referring to an epoll instance have been closed, the kernel destroys the instance and releases the associated resources for reuse.
  • Epoll_ctl() performs control operations on the epoll instance referred to by the file descriptor epfd. It requests that the operation op be performed for the target file descriptor, fd. Valid values for the op argument are :
  • EPOLL_CTL_ADD
    Register the target file descriptor fd on the epoll instance referred to by the file descriptor epfd and associate the event event with the internal file linked to fd.
  • EPOLL_CTL_MOD
    Change the event event associated with the target file descriptor fd.
  • EPOLL_CTL_DEL
    Remove (deregister) the target file descriptor fd from the epoll instance referred to by epfd. The event is ignored and can be NULL.
  • Epoll_wait() system call waits for events on the epoll(7) instance referred to by the file descriptor epfd. The memory area pointed to by events will contain the events that will be available for the caller. Up to maxevents are returned by epoll_wait(). The maxevents argument must be greater than zero. The timeout argument specifies the minimum number of milliseconds that epoll_wait() will block. Specifying a timeout of -1 causes epoll_wait() to block indefinitely, while specifying a timeout equal to zero cause epoll_wait() to return immediately, even if no events are available. The data of each returned structure will contain the same data the user set with an epoll_ctl(2) (EPOLL_CTL_ADD,EPOLL_CTL_MOD) while the events member will contain the returned event bit field.

总结一下上面的引用:epoll_create用来创建一个实例,返回的efd指向这个实例。epoll_ctl将自己感兴趣的fd注册到epoll_create所创建的实例上并和自己感兴趣的event绑定。epoll_wait等待参数epfd所指定的实例上事件的发生,**epoll与select或者poll相似,笔者推测都是在内核中进行了短期的轮询,也就是保证返回就绪的fd大于等于1。**其他的知识,比如Edge Triggered以后还会继续深入。
  无论使用哪个函数,无论epoll做了什么样的改进,总体来说以上三个函数都是同步的。阻塞是否由参数决定,所以使用上述三个函数返回以后,必须人为轮询其对应返回事件或者fd值域。

3. 实验部分

笔者出题:分别使用select, poll, epoll实现回显程序

>NOTE : 本题目和本身上述三个函数用于socket编程的思路无关,单纯对其使用特性的简单尝试。不增加篇幅,单独记录。对以上内容有质疑,请及时指正。   
韦来生《数理统计》课后习题与答案 韦来生经典教材《数理统计》的课后习题与答案,分享给大家希望能有所帮助~ 立即下载

相关推荐

高等数理统计 应用数理统计

高等数理统计 高等数理统计高等数理统计高等数理统计高等数理统计

高等数理统计_高等数理统计习题解答——第二章

第二章:随机变量的函数的分布 1.已知随机变量的密度函数为:试找出一个单调函数,使得随机变量服从上的均匀分布.:注意到的概率积分变换服从上的均匀分布: 故: 4.已知和服从上的均匀分布,且相互独立。(a) 试求的密度函数;(b) 试求的密度函数。:(a): 当 时: 当 时: (b): 当 时: 6.已知随机变量和的联合密度函数为:(a) 试求和的联合密度函数;(b) 证明和相互独立....

weixin_39628945的博客 309

概率论与数理统计(茆诗松)第二版课后习题参考答案.pdf

主要内容包括:随机事件与概率,随机变量及其分布,随机变量的数字特征,统计量及其分布,参数估计,假设检验,方差分析与回归分析等。

概率论与数理统计(第二版) 吴传生 编 高等教育出版社 大学课后习题答案

跟多答案:http://www.daanbar.com/book-info/2551.html概率论与数理统计(第二版)吴传生 编高等教育出版社第1章:随机事件的概率第2章:一维随机变量及其分布第3章:多维随机变量及其分布第4章:随机变量的数字特征第5章:大数定律和中心极限定律第6章:样本及抽样分布第7章:参数估计第8章:假设检验第9章:线性回归分析与方差分析补充习题参考答案期末考试复习资料及试题...

dinggang007的专栏 5273

高等数理统计(茆诗松)

大数据研究的基础知识,对数理统计、概率论等相关知识有详细解释

中科院研究生院高等数理统计讲义作业以及答案(张三国老师)

中科院研究生院高等数理统计讲义作业以及答案(张三国老师),非常详细,课件非常好,还有配套的作业题目 中科院研究生院高等数理统计讲义作业以及答案(张三国老师),非常详细,课件非常好,还有配套的作业题目

高等数理统计_高等数理统计习题解答——第三章

第三章:各种收敛方式与极限分布 3.已知随机变量 独立同分布于 ,令 。(a) 试求 的矩母函数;(b) 试求 的极限分布。:(a): 由题可知: 的矩母函数为 则有 的矩母函数为 (b): 这正是标准正态分布所对应的矩母函数,从而 的极限分布为标准正态分布5.已知随机变量 独立同分布于 ,令 。(a) 试求 的矩母函数;(b) 试求 的矩母函数;(c) 试求 的极限分布。...

weixin_39881802的博客 1130

概率论与数理统计教程第二版(魏宗舒著)高等教育出版社课后答案汇编.pdf

概率论与数理统计教程第二版(魏宗舒著)高等教育出版社课后答案汇编.pdf

高级IO和5种IO模型

高级IO详解

m0_65558082的博客 1516

ubuntu20.4源码安装最新gcc(gcc V12.2)

Ubuntu20.4自带的gcc为V9.4.0的版本,老版本的gcc存在不支持新版本C语言规范,在配置、编译、安装应用软件或工具时,可能存在不能正确安装的问题。(比如:libpqxx-7.7.4在配置时要求c++17版本的支持,但gcc V9.4.0版本不支持c++17)。因此本文介绍ubuntu20.4的系统下载最新gcc12.2版本源码,并进行本地编译、安装。本节内容包括gcc12.2的必备库安装和gcc12.2安装两部分内容组成。

q544344318的博客 1万+

win11一直弹出用户账户控制怎么解决

用户帐户控制简称UAC,是微软公司在其Windows Vista及更高版本操作系统中采用的一种控制机制。近期有部分Win11用户想要关闭UAC,但是不知道应该如何操作,对此下面我就教给大家操作方法,大家可以去尝试看看。...

xitongzhijia_abc的博客 5万+

IO多路复用-select poll pselect epoll分析

1.I/O模型 Linux平台下有5中I/O模型,分别为阻塞式I/O、非阻塞式I/O、I/O复用、信号驱动式I/O及异步I/O。本节内容参考自《UNIX网络编程》。 (1)阻塞式I/O模型 最流行的I/O模型是阻塞式I/O模型。一般情况下,默认的IO都是阻塞的。以UDP套接字为例,当进程调用recvfrom系统调用,直到数据被复制到应用进程的缓冲区或者发生错误才返回,常见的系统调用是被系统中断。若内核中的数据还未准备好,则调用recvfrom的进程被阻塞。 (2)非阻塞式I/O模型 非阻塞式I/O需要显示

非专业业余程序员 596

从Datasheet到可用的Verilog模块:手把手教你为N25Q128 SPI Flash写状态机驱动

本文详细介绍了如何从Datasheet到实现可用的Verilog模块,手把手教你为N25Q128 SPI Flash编写状态机驱动。文章涵盖SPI Flash的核心工作机制、数据手册解析方法、Verilog状态机设计实践以及调试与性能优化技巧,特别适合FPGA开发者和硬件设计工程师参考。

weixin_30596023的博客 179

linux基础编程:IO模型:阻塞/非阻塞/IO复用 同步/异步 Select/Epoll/AIO

IO概念 Linux的内核将所有外部设备都可以看做一个文件来操作。那么我们对与外部设备的操作都可以看做对文件进行操作。我们对一个文件的读写,都通过调用内核提供的系统调用;内核给我们返回一个file descriptor(fd,文件描述符)。而对一个socket的读写也会有相应的描述符,称为socketfd(socket描述符)。描述符就是一个数字,指向内核中一个结构体(文件路径,数据区,

xiaohuima_dong的专栏 1079

RK3576平台部署NanoTrack:边缘AI视觉跟踪实战指南

边缘AI部署是将深度学习模型在资源受限的嵌入式设备上高效运行的关键技术,其核心在于模型压缩、硬件适配与软件栈优化。通过INT8量化、算子融合与内存优化等原理,能显著降低模型计算量与内存占用,从而在嵌入式NPU上实现实时推理。这项技术的价值在于为安防监控、无人机视觉、工业检测等场景提供低功耗、高响应的智能感知能力。以瑞芯微RK3576平台部署轻量级视觉跟踪模型NanoTrack为例,其过程涉及模型结构分析、RKNN工具链转换、C++推理程序开发及多线程性能优化,完整展现了从算法到产品的工程化路径,为开发者提供

weixin_31887307的博客 429

2017–2024年中国10米/20米分辨率水稻种植分布数据集

摘要:本数据集提供2017-2024年中国23个省级行政区的水稻种植分布数据,包含单季稻和双季稻分类(GeoTIFF格式,WGS84坐标系)。5个省份分辨率为20米,其余为10米,基于Sentinel卫星数据和TWDTW方法生成。数据公开共享(7.99GB),使用需注明来源并引用相关文献(DOI:10.12199/nesdc.ecodb.rs.2025.012)。涉及学科包括遥感、生态学和地理学,研究成果需发送至国家生态科学数据中心备案。

国科大硕士在读,分享Python/GEE/Matlab/R专业代码实践,涵盖数据分析、算法开发与应用技巧等,以代码会友。 1389

Unix环境高级编程学习笔记(九) 高级IO

fcntl 记录锁 很多时候,当我们有多个进程要访问同一个文件的时候,为了防止多进程访问导致的不一致,我们就要考虑进程间的同步问题了。fcntl是一个非常强大的函数,在这里我们可以使用它来给文件的某一个部分上锁。先来看一下它的声明: int fcntl(int filedes, int cmd, ... /* struct flock *flockptr */ ); 很显然,这是一个拥有

justaipanda的专栏 7798

IoT安全软件:Forescout二次开发_Forescout基础架构与原理

Forescout平台是一个集成了多种安全功能的综合解决方案,旨在帮助组织管理和保护其网络中的IoT设备。该平台通过自动发现、分类和监控网络中的设备,提供实时的安全可见性和控制。Forescout的核心优势在于其能够处理混合环境中的各种设备,包括传统IT设备、IoT设备和OT设备。Forescout平台由多个核心组件组成,每个组件负责特定的功能。了解这些组件的运作机制是进行二次开发的基础。假设我们需要定义一个策略,禁止所有厂商为XYZ的设备访问互联网。选择策略类型。

chenlz2007的博客 1965

[高等数学]同济版高等数学【第七版】上下册教材+习题全解PDF

链接:https://pan.baidu.com/s/1gyy-GMGjwguAjYijrpC8RA?高等数学 同济第7版 上册 习题全解指南 课后习题答案解析 链接:pan.baidu.com/s/1qLr4Nb。高等数学 同济第7版 下册 习题全解指南 课后习题答案解析 链接:pan.baidu.com/s/1aJXk8N。概率论与数理统计 第四版浙江大学 链接:pan.baidu.com/s/1wr_1L3。高等数学 第7版 上册 同济大学 链接:pan.baidu.com/s/1jhIjcu。

十二_的博客 5万+

C#串口通信从入门到精通(5)——打开、关闭串口

本文详细介绍如何打开串口

qq_34059233的博客 6786

【Python_Zebra斑马打印机编程学习笔记(二)】基于BarTender将btw文件转换为zpl文件

本文介绍如何基于 BarTender 软件将 btw 格式的文件转换为 zpl 格式的文件,有需要的读者可以点赞收藏,也欢迎在评论区进行讨论。

禾戊之昂的博客 3378

pselect 和 select

然而当pselect函数返回时,进程的信号掩码又被重置为调用pselect之前的值(即SIGINT被阻塞),也就是说只有在pslecet中,SIGINT是不被阻塞的。有sigmask的时候,pselect相当于如下的select()函数,在进入select()函数之前手动将信号的掩码改变,并保存之前的掩码值;注意: pselect(...,&zeromask) 与 pselect(...,NULl) 意义完全不同,前者是在调用期间不阻塞任何新信号,后者和调用select相同,保持原来的信号mask。...

木牛的博客 1630

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

select与poll的异同

另外,在一些平台上,select 函数会有一些问题,例如无法正确处理大于 1024 的文件描述符数量等,但是这些问题并不影响 poll 函数的使用。select 函数每次调用时都需要将待检测的文件描述符集合拷贝到内核中去,而 poll 函数则是通过参数传递文件描述符集合,不需要对文件描述符集合进行操作。参数形式不同: select 函数使用 fd_set 类型的描述符集合来传递需要监视的文件描述符列表,而 poll 函数使用 struct pollfd 数组类型来指定需要监听的文件描述符及其感兴趣的事件。

最后一个bug的博客 2037

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Linux网络编程--select()和pselect()函数

函数select()与之前的recv()和send()直接操作文件描述符不同。使用select()函数可以先对需要操作的文件描述符进行查询,查看是否目标文件描述符可以进行读、写或者错误操作,然后当文件描述符满足操作的条件的时候才进行真正的IO操作。函数select()是用一种超时轮循的方式来查看文件的读写错误可操作性。在Linux下,还有一个相似的函数pselect()。函数select()和pselect()用于IO复用,它们监视多个文件描述符的集合,判断是否有符合条件的时间发生。...

木牛的博客 1045

IO函数之select()与pselect()、poll()与ppoll()简介

一:select()函数 select()函数与recv()和send()等直接操作文件描述符不同,它是对需要操作的文件描述符进行一个查询和监控的一个作用。

huang422600的博客 2091

select和pselect学习笔记

简介 select、pselect用于同步I/O多路复用。select、pselect允许程序同时监听多个fd,直到其中一个或多个fd上有对应的I/O操作就绪时,或超时时才返回。 函数原型介绍 辅助宏函数 FD_CLR void FD_CLR(int fd, fd_set *set); 从集合set中删除fd FD_ISSET int FD_ISSET(int fd, fd_set *set); 判断集合set中是否已经设置了fd FD_SET void FD_SET(int fd, fd_set *

zxc3590235的博客 1459
上一篇: 网络编程之Sockets Introduction(二)
下一篇: 高级IO之简单的select_poll_epoll实验(五)
LoveStackover
博客等级 码龄9年 14粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值