IO多路复用接口Linux内核源码剖析,源码之前,了无秘密
Linux select内核源码剖析
select的原理其实是和poll是一样的,都是采用轮询的方式。select相对于poll也许是比较节省空间吧,因为select是采用bitmap来标志的
本文先讲解一下如何在应用层使用select,然后再深入内核剖析select机制
select应用程序
select可以监听多个文件描述符,直到条件满足或者超时返回
-
select函数原型
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
nfds:最大的文件描述符加1
readfds:监听可读集合
writefds:监听可写集合
exceptfds:监听异常集合
timeout:超时时间
对于这些集合,有一组函数可以进行设置
void FD_SET(int fd, fd_set *set); //设置文件描述符到集合中 void FD_CLR(int fd, fd_set *set); //从集合中清除文件描述符标志 int FD_ISSET(int fd, fd_set *set); //判断文件描述符在集合中是否被标志 void FD_ZERO(fd_set *set); //清空集合
demo
下面这个程序使用select监听标准输入,直到标准输入可读时,返回并打印内容
#include <stdio.h>
#include <sys/select.h>
int main(int argc, char* argv[])
{
fd_set rfds;
int nfds;
int i;
char buf[1024];
int len;
FD_ZERO(&rfds); //清空集合
FD_SET(0, &rfds); //标准输入
nfds = 0 + 1; //最大文件描述符加1
while(1)
{
fd_set fds = rfds;
/* 开始监听 */
if(select(nfds, &fds, NULL, NULL, NULL) < 0)
{
printf("select err.\n");
return -1;
}
for(i = 0; i < nfds