int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout);
对于第一个参数 nfds
,这是我从 wiki 得到的:
This is an integer one more than the maximum of any file descriptor in any of the sets. In other words, while adding file descriptors to each of the sets, you must calculate the maximum integer value of all of them, then increment this value by one, and then pass this as nfds.
我有一个简单的问题:
如果我有多个socket需要处理,select
的第一个参数应该怎么设置?
是否应该设置为最大套接字号+1?
如果是,是否意味着 select
正在监听所有小于最大套接字号 + 1 的文件描述符?
例如,我有三个套接字:111、222 和 333。如果我将第一个参数设置为 334,是否意味着我正在监听从 0 到 333 的所有文件描述符?
最佳答案
Should I set it with the largest socket number + 1?
是的!
If so, does it mean that the select is listening all of file descriptors which is less than the largest socket number + 1?
不,它只对列出的 fd_sets 执行操作 readfds、writefds 和 exceptfds
For example, I have three sockets: 111, 222 and 333. If I set the first parameter as 334, does it mean that I'm listening all of file descriptors from 0 to 333?
不,你只是在 111、222 和 333 上做 $select$。
在内部 sys_select 设置 3 个位图,三个位集中的每个位都设置为 1,然后如果设置了这些位中的任何一个(这又对应于文件描述符操作),则 wait_key_set
对其执行操作。
这个接口(interface)的原因是在内核中它变成了一个非常可预测的 for 循环;使其工作起来非常安全;而不是试图在内核内部进行计算。
关于c - linux:select的第一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38021685/