select函数源码简析
来源:互联网 发布:阿里云 微信小程序 编辑:程序博客网 时间:2024/06/18 15:39
1 简介
select()
允许一个程序监听多个文件描述符,等待一个或者多个文件描述符的I/O操作变成“就绪”状态(比如:可读)。
/* According to POSIX.1-2001 */#include <sys/select.h>/* According to earlier standards */#include <sys/time.h>#include <sys/types.h>#include <unistd.h>int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);void FD_CLR(int fd, fd_set *set);int FD_ISSET(int fd, fd_set *set);void FD_SET(int fd, fd_set *set);void FD_ZERO(fd_set *set);#include <sys/select.h>int pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *timeout, const sigset_t *sigmask);
int nfds
参数表示待监听的集合里的最大文件描述符的值 + 1。
fd_set *readfds
、fd_set *writefds
、fd_set *exceptfds
三个集合分别存放需要监听读、写、异常三个操作的文件描述符。
struct timeval *timeout
表示超时时间。设为0则立刻扫描并返回,设为NULL则永远等待,直到有文件描述符就绪。
2 SYSCALL_DEFINE5(select, …
阅读的Linux内核版本:linux-2.6.32.68
select源码位于fs/select.c文件
SYSCALL_DEFINE5(select, int, n, fd_set __user *, inp, fd_set __user *, outp, fd_set __user *, exp, struct timeval __user *, tvp){ struct timespec end_time, *to = NULL; struct timeval tv; int ret; if (tvp) { if (copy_from_user(&tv, tvp, sizeof(tv))) return -EFAULT; to = &end_time; if (poll_select_set_timeout(to, tv.tv_sec + (tv.tv_usec / USEC_PER_SEC), (tv.tv_usec % USEC_PER_SEC) * NSEC_PER_USEC)) //微秒转纳秒 return -EINVAL; } ret = core_sys_select(n, inp, outp, exp, to); ret = poll_select_copy_remaining(&end_time, tvp, 1, ret); return ret;}
select函数执行从此开始,关键调用流程如下: select -> core_sys_select() -> do_select() 。
selcet的主要操作在do_select()
函数中完成。
在上述函数中,主要把超时时间tvp
的值从用户空间复制到内核空间,并且调用poll_select_set_timeout()
函数把超时时间的长度加到当前时间上,获得最终的结束时间点to
。由于poll_select_set_timeout()
的时间精度是纳秒,所以需要转换。
之后调用core_sys_select()
函数执行主要逻辑。
在主要程序执行完之后,还会调用poll_select_copy_remaining()
把等待时间中的剩余时间返回给用户态的tvp
。
3 core_sys_select()
/* * We can actually return ERESTARTSYS instead of EINTR, but I'd * like to be certain this leads to no problems. So I return * EINTR just for safety. * * Update: ERESTARTSYS breaks at least the xview clock binary, so * I'm trying ERESTARTNOHAND which restart only when you want to. */#define MAX_SELECT_SECONDS \ ((unsigned long) (MAX_SCHEDULE_TIMEOUT / HZ)-1)int core_sys_select(int n, fd_set __user *inp, fd_set __user *outp, fd_set __user *exp, struct timespec *end_time){ fd_set_bits fds; void *bits; int ret, max_fds; unsigned int size; struct fdtable *fdt; /* Allocate small arguments on the stack to save memory and be faster */ long stack_fds[SELECT_STACK_ALLOC/sizeof(long)]; ret = -EINVAL; if (n < 0) goto out_nofds; /* max_fds can increase, so grab it once to avoid race */ rcu_read_lock(); fdt = files_fdtable(current->files); max_fds = fdt->max_fds; rcu_read_unlock(); if (n > max_fds) //不能大于最大描述符限制 n = max_fds; /* * We need 6 bitmaps (in/out/ex for both incoming and outgoing), * since we used fdset we need to allocate memory in units of * long-words. */ size = FDS_BYTES(n); bits = stack_fds; if (size > sizeof(stack_fds) / 6) { //如果在栈中分配的空间不够存放,则通过kmalloc存放 /* Not enough space in on-stack array; must use kmalloc */ ret = -ENOMEM; bits = kmalloc(6 * size, GFP_KERNEL); if (!bits) goto out_nofds; } fds.in = bits; fds.out = bits + size; fds.ex = bits + 2*size; fds.res_in = bits + 3*size; fds.res_out = bits + 4*size; fds.res_ex = bits + 5*size; if ((ret = get_fd_set(n, inp, fds.in)) || (ret = get_fd_set(n, outp, fds.out)) || (ret = get_fd_set(n, exp, fds.ex))) goto out; zero_fd_set(n, fds.res_in); zero_fd_set(n, fds.res_out); zero_fd_set(n, fds.res_ex); ret = do_select(n, &fds, end_time); if (ret < 0) goto out; if (!ret) { ret = -ERESTARTNOHAND; if (signal_pending(current)) goto out; ret = 0; } if (set_fd_set(n, inp, fds.res_in) || set_fd_set(n, outp, fds.res_out) || set_fd_set(n, exp, fds.res_ex)) ret = -EFAULT;out: if (bits != stack_fds) kfree(bits);out_nofds: return ret;}
core_sys_select()
函数主要为真正的select操作分配存储空间。这里分配了一个名为stack_fds
的long
长整型集合。首先预分配了long stack_fds[SELECT_STACK_ALLOC/sizeof(long)];
,根据
#define FRONTEND_STACK_ALLOC 256#define SELECT_STACK_ALLOC FRONTEND_STACK_ALLOC
可以看到stack_fds
的大小为 256bit 。
之前存放文件描述符集合的类型是fd_set
,根据
typedef __kernel_fd_set fd_set;
#undef __NFDBITS#define __NFDBITS (8 * sizeof(unsigned long))#undef __FD_SETSIZE#define __FD_SETSIZE 1024#undef __FDSET_LONGS#define __FDSET_LONGS (__FD_SETSIZE/__NFDBITS)#undef __FDELT#define __FDELT(d) ((d) / __NFDBITS)#undef __FDMASK#define __FDMASK(d) (1UL << ((d) % __NFDBITS))typedef struct { unsigned long fds_bits [__FDSET_LONGS];} __kernel_fd_set;
可以看到 fd_set
类型在内核里是实际上__kernel_fd_set
结构体,里面只包含了一个unsigned long
类型的数组fds_bits
。这个数组的大小是 1024/(8 * sizeof(unsigned long)) ,也就是这个数组占用空间为 1024bit 。在select中文件描述符在集合里是以位图的形式存在的,把文件描述符存放在三个集合中,最大直到 1023 ,也就是只能监听最多 1024 个文件描述符,并且只能是0 ~ 1023。
所以,存放文件描述符的数据结构限制了 select() 最多只能监听 1024 个文件描述符。
回到刚刚core_sys_select()
里的stack_fds
数组,这个变量的占用空间大小是 256*sizeof(long) bit 。
根据We need 6 bitmaps (in/out/ex for both incoming and outgoing)
以及代码可以看到,stack_fds
要存放的是6个位图,分别对应用户态传入的存放监听读、写、异常三个操作的文件描述符集合,以及这三个操作在select执行过后需要返回的三个集合。
这是 select 的机制,每次执行 select() 之后,函数把“就绪”的文件描述符留下,返回。下一次,再次执行 select() 时,需要重新把需要监听的文件描述符传入。
我认为,如果要节约空间,完全可以在传入的三个集合中进行删减,不必浪费三个集合的空间。(我的想法,可能有其他问题。)
如果刚从栈中分配的stack_fds
不够存放6个集合的数据,那么再从 kmalloc 分配(用于分配大空间)。
6个集合分别用指针指向stack_fds
中的不同部分空间,依次利用。size
为间隔大小。
根据
/* * How many longwords for "nr" bits? */#define FDS_BITPERLONG (8*sizeof(long))#define FDS_LONGS(nr) (((nr)+FDS_BITPERLONG-1)/FDS_BITPERLONG)#define FDS_BYTES(nr) (FDS_LONGS(nr)*sizeof(long))
size = FDS_BYTES(n);
它的大小是((((n)+(8*sizeof(long))-1)/(8*sizeof(long)))*sizeof(long))
,以32位系统为例,long
为8字节,则大小为((((n)+8*8-1)/(8*8))*8)
化简为(n-1)/8 + 8
。n
是用户态程序指定的最大描述符+1,如果我要监听的最大文件描述符为7, n 为8,由于这是整型运算,则结果为 8 。也就是确保能存下所有描述符,而且大小为 8 的倍数 。所以kmalloc
分配的空间6个集合是可以存放下去的。
之后从用户态空间把集合数据拷贝过来,并且初始化用于输出的3个位图空间为0。
进入do_select()
函数。
4 select()
int do_select(int n, fd_set_bits *fds, struct timespec *end_time){ ktime_t expire, *to = NULL; struct poll_wqueues table; poll_table *wait; int retval, i, timed_out = 0; unsigned long slack = 0; rcu_read_lock(); retval = max_select_fd(n, fds); //获取最大文件描述符 rcu_read_unlock(); if (retval < 0) return retval; n = retval; poll_initwait(&table); //初始化用于等待操作的数据,当文件描述符就绪时会回调 wait = &table.pt; if (end_time && !end_time->tv_sec && !end_time->tv_nsec) { wait = NULL; timed_out = 1; } if (end_time && !timed_out) slack = estimate_accuracy(end_time); retval = 0; for (;;) { unsigned long *rinp, *routp, *rexp, *inp, *outp, *exp; inp = fds->in; outp = fds->out; exp = fds->ex; rinp = fds->res_in; routp = fds->res_out; rexp = fds->res_ex; for (i = 0; i < n; ++rinp, ++routp, ++rexp) { //遍历每个描述符 unsigned long in, out, ex, all_bits, bit = 1, mask, j; unsigned long res_in = 0, res_out = 0, res_ex = 0; const struct file_operations *f_op = NULL; struct file *file = NULL; in = *inp++; out = *outp++; ex = *exp++; all_bits = in | out | ex; if (all_bits == 0) { i += __NFDBITS; continue; } for (j = 0; j < __NFDBITS; ++j, ++i, bit <<= 1) { //遍历长字里的每个位 32位下是8*4=32 int fput_needed; if (i >= n) break; if (!(bit & all_bits)) continue; file = fget_light(i, &fput_needed); //从文件描述符获取文件结构体 if (file) { f_op = file->f_op; mask = DEFAULT_POLLMASK; if (f_op && f_op->poll) { wait_key_set(wait, in, out, bit); mask = (*f_op->poll)(file, wait); //这是关键 调用文件对应的poll操作 } fput_light(file, fput_needed); if ((mask & POLLIN_SET) && (in & bit)) { res_in |= bit; retval++; wait = NULL; } if ((mask & POLLOUT_SET) && (out & bit)) { res_out |= bit; retval++; wait = NULL; } if ((mask & POLLEX_SET) && (ex & bit)) { res_ex |= bit; retval++; wait = NULL; } } } if (res_in) *rinp = res_in; if (res_out) *routp = res_out; if (res_ex) *rexp = res_ex; cond_resched(); //将调度一个新的程序运行,设置need_resched后生效 } wait = NULL; if (retval || timed_out || signal_pending(current)) break; if (table.error) { retval = table.error; break; } /* * If this is the first loop and we have a timeout * given, then we convert to ktime_t and set the to * pointer to the expiry value. */ if (end_time && !to) { expire = timespec_to_ktime(*end_time); to = &expire; } if (!poll_schedule_timeout(&table, TASK_INTERRUPTIBLE, to, slack)) timed_out = 1; } poll_freewait(&table); //移除所有文件中的等待 return retval;}
在do_select()
里面,主要是一遍一遍循环遍历每一个文件描述符,查询哪一个为就绪状态。
在外层的循环for (;;)
,每一次是整个集合遍历一遍。这是死循环,直到达到触发条件 1.有就绪的文件描述符 2.超时 3.中断。第一遍之后,当前进程会进入睡眠状态,以节约资源,直到下一次被唤醒(由文件描述符变为就绪状态触发唤醒)。
第二层的for (i = 0; i < n; ++rinp, ++routp, ++rexp) {
循环,每一次是遍历__NFDBITS
个描述符,这是由第三层循环决定的。从i < n
可知,因为函数只会循环到 n-1 ,所以才需要输入的最大文件描述符值nfds
+ 1 。
第三层for (j = 0; j < __NFDBITS; ++j, ++i, bit <<= 1) {
循环每次遍历一个 bit 即一个文件描述符,遍历__NFDBITS
次。
根据:
#undef __NFDBITS#define __NFDBITS (8 * sizeof(unsigned long))
可以看到,遍历的数量就是8个unsigned long长度。因为对于位图,可以一次比较多位,都没有需要监听的文件描述符就跳过,以加快速度。
循环里先根据文件描述符获得文件结构体,然后调用结构体里f_op
中挂载的poll
函数,以获取就绪信息。可以看到select的功能依赖文件的驱动实现。mask = (*f_op->poll)(file, wait);
是 select 的关键,这里不仅检测了文件是否就绪,而且还把当前进程加入等待队列,如果该文件描述符就绪,则会触发回调,以及唤醒该进程。这需要该文件挂载的驱动配合的。
retval
变量用于累计“就绪”的文件描述符数量,包括3个集合所有的。
一整次扫描完成的最后,调用poll_schedule_timeout
函数,如果还未超时,则进入睡眠,等待就绪的文件描述符唤醒。超时则,timed_out = 1;
。所以可以看到
if (retval || timed_out || signal_pending(current)) break;
此处为跳出循环的代码,也就是在超时之后,还要再循环一次才能跳出。
最后跳出循环后,调用poll_freewait(&table);
移出等待队列。
可以看出来,select 的开销大在于每次都要遍历扫描每一个文件描述符就绪状态,并且是从最小的描述符 0 开始比较,做了很多无用功,所以效率很低。随着文件描述符的增加,效率会越来越低。
- select函数源码简析
- select函数的实现源码
- I/O复用--select函数源码剖析
- JQuery3.1.1源码解读(五)【select 函数】
- Select()函数
- select函数
- select函数
- select函数
- select函数
- select()函数
- 函数select
- select函数
- select 函数
- select函数
- select 函数
- select函数
- select函数
- select函数
- 设有n个正整数,将他们连接成一排,组成一个最小的多位整数
- 使用CSS3代替SVG中的animateTransform
- ByteArrayOutputstream与FileOutputstream
- 游标的那些事
- C#索引器
- select函数源码简析
- Fuzz安全狗注入绕过
- 2017 Multi-University Training Contest
- AS自带模拟器 Your GPU driver information
- linux系统mysql数据库基本命令
- Cuckoo for Hashing--关于哈希表的练习
- 关于使用c# Sqlite的问题
- shell脚本--if判断(数字条件、字符串条件)
- 支付密码的效果