select使用实例

本文通过一个实例介绍了select函数在多路复用中的应用。讲解了阻塞与非阻塞模式的select,并展示了如何处理读取文件描述符时的三种不同情况。文中提到,通过四个client同时连接同一server,证明了select的多路复用能力,但同时也指出select仅支持LT模式,可能导致需要多次触发IO事件来完成数据读取。
摘要由CSDN通过智能技术生成

select函数是多路复用的一种,本文我们给出一个select的通信实例,看下select的代码如何组织,先上代码:

#include <unistd.h>
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <errno.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <fcntl.h>
#include <signal.h>
//设置文件描述符为非阻塞,避免读文件时阻塞
int setNonblock(int fd){
   
    int flags = fcntl(fd, F_GETFL, 0);
    if(flags < 0){
   
        std::cout << "F_GETFL failed:" << strerror(errno) << std::endl;
        return -1;
    }
    flags = flags | O_NONBLOCK;
    if(fcntl(fd, F_SETFL, flags)<0){
   
        std::cout << "set nonblock failed:" << strerror(errno) << std::endl;
        return -1;
    }
    return 0;
}
int main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值