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(){
//初始化socket