一、poll和seclect机制的区别
select
was introduced in BSD Unix, released in August 1983, whereaspoll
was introduced in SVR3 Unix, released in 1986.- Operations in
poll
andselect
is linear and slow because of having a lot of checks. - The main advantage of select is the fact that it is very portable – every UNIX-like OS has it. Some Unix systems do not support
poll
. - With
select
, the file descriptor sets are reconstructed on return, so each subsequent call must reinitialize them. Thepoll
system call separates the input (events field) from the output (revents
field), allowing the array to be reused without change. - The timeout parameter to
select
is undefined on return. So, we need to reinitialize it. poll
does not require the user to calculate the value of the highest-numbered file descriptor +1. Whereas in select, we have to calculate thenfds
or pass the maximum number usingFD_SETSIZE
.poll
is more efficient for large-valued file descriptors. For example, when you want to wait for the events in the file descriptor (fd
) 1000, poll will directly use thatfd
. But if you use this 1000fd
in select, it has to iterate (loop) from 0 to 999 to check any file has data.- In the
select
, we need to iterate over the file descriptors to check if it exists on the set returned from select. But in thepoll
, we can check only we wanted to. - In the
poll
, you can use the file descriptor which is more than 1024. But inselect
you cannot use it. If you use the file descriptor which is more than or equal to 1024 (FD_SETSIZE
), then it may destroy your stack. How?select
’s file descriptor sets are statically sized.
用一句更通俗的话来说:select和poll机制驱动侧实现原理一致,都依赖于file_operation结构里面的poll函数实现。主要区别在于应用层的API不一样。
二、seclect机制的应用层API
int select( int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout );
Where,
nfds
– This argument should be set to the highest-numbered file descriptor in any of the three sets, plus 1. The indicated file descrip