|
| 1 | +## 1、I/O 模型 |
| 2 | + |
| 3 | +**一个输入操作通常包括两个阶段:** |
| 4 | + |
| 5 | +- 等待数据准备好 |
| 6 | +- 从内核向进程复制数据 |
| 7 | + |
| 8 | +对于一个套接字上的输入操作,第一步通常涉及等待数据从网络中到达。当所等待数据到达时,它被复制到内核中的某个缓冲区。第二步就是把数据从内核缓冲区复制到应用进程缓冲区。 |
| 9 | + |
| 10 | +Unix 有五种 I/O 模型: |
| 11 | + |
| 12 | +- 阻塞式 I/O |
| 13 | +- 非阻塞式 I/O |
| 14 | +- I/O 复用(select 和 poll) |
| 15 | +- 信号驱动式 I/O(SIGIO) |
| 16 | +- 异步 I/O(AIO) |
| 17 | + |
| 18 | +### 1.1阻塞式 I/O |
| 19 | + |
| 20 | +应用进程被阻塞,直到数据从内核缓冲区复制到应用进程缓冲区中才返回。 |
| 21 | + |
| 22 | +应该注意到,在阻塞的过程中,其它应用进程还可以执行,因此阻塞不意味着整个操作系统都被阻塞。因为其它应用进程还可以执行,所以不消耗 CPU 时间,这种模型的 CPU 利用率会比较高。 |
| 23 | + |
| 24 | +下图中,recvfrom() 用于接收 Socket 传来的数据,并复制到应用进程的缓冲区 buf 中。这里把 recvfrom() 当成系统调用。 |
| 25 | + |
| 26 | +```cpp |
| 27 | +ssize_t recvfrom( |
| 28 | +int sockfd, void *buf, |
| 29 | +size_t len, int flags, |
| 30 | +struct sockaddr *src_addr, |
| 31 | +socklen_t *addrlen); |
| 32 | +``` |
| 33 | +
|
| 34 | + |
| 35 | +
|
| 36 | +### 1.2非阻塞式 I/O |
| 37 | +
|
| 38 | +应用进程执行系统调用之后,内核返回一个错误码。应用进程可以继续执行,但是需要不断的执行系统调用来获知 I/O 是否完成,这种方式称为轮询(polling)。 |
| 39 | +
|
| 40 | +由于 CPU 要处理更多的系统调用,因此这种模型的 CPU 利用率比较低。 |
| 41 | +
|
| 42 | + |
| 43 | +
|
| 44 | +### 1.3I/O 复用 |
| 45 | +
|
| 46 | +使用 select 或者 poll 等待数据,并且可以等待多个套接字中的任何一个变为可读。这一过程会被阻塞,当某一个套接字可读时返回,之后再使用 recvfrom 把数据从内核复制到进程中。 |
| 47 | +
|
| 48 | +它可以让单个进程具有处理多个 I/O 事件的能力。又被称为 Event Driven I/O,即事件驱动 I/O。 |
| 49 | +
|
| 50 | +如果一个 Web 服务器没有 I/O 复用,那么每一个 Socket 连接都需要创建一个线程去处理。如果同时有几万个连接,那么就需要创建相同数量的线程。相比于多进程和多线程技术,I/O 复用不需要进程线程创建和切换的开销,系统开销更小。 |
| 51 | +
|
| 52 | + |
| 53 | +
|
| 54 | +### 1.4信号驱动 I/O |
| 55 | +
|
| 56 | +应用进程使用 sigaction 系统调用,内核立即返回,应用进程可以继续执行,也就是说等待数据阶段应用进程是非阻塞的。内核在数据到达时向应用进程发送 SIGIO 信号,应用进程收到之后在信号处理程序中调用 recvfrom 将数据从内核复制到应用进程中。 |
| 57 | +
|
| 58 | +相比于非阻塞式 I/O 的轮询方式,信号驱动 I/O 的 CPU 利用率更高。 |
| 59 | +
|
| 60 | + |
| 61 | +
|
| 62 | +### 1.5异步 I/O |
| 63 | +
|
| 64 | +应用进程执行 aio_read 系统调用会立即返回,应用进程可以继续执行,不会被阻塞,内核会在所有操作完成之后向应用进程发送信号。 |
| 65 | +
|
| 66 | +异步 I/O 与信号驱动 I/O 的区别在于,异步 I/O 的信号是通知应用进程 I/O 完成,而信号驱动 I/O 的信号是通知应用进程可以开始 I/O。 |
| 67 | +
|
| 68 | + |
| 69 | +
|
| 70 | +### 1.6五大 I/O 模型比较 |
| 71 | +
|
| 72 | +- 同步 I/O:将数据从内核缓冲区复制到应用进程缓冲区的阶段(第二阶段),应用进程会阻塞。 |
| 73 | +- 异步 I/O:第二阶段应用进程不会阻塞。 |
| 74 | +
|
| 75 | +同步 I/O 包括阻塞式 I/O、非阻塞式 I/O、I/O 复用和信号驱动 I/O ,它们的主要区别在第一个阶段。 |
| 76 | +
|
| 77 | +非阻塞式 I/O 、信号驱动 I/O 和异步 I/O 在第一阶段不会阻塞。 |
| 78 | +
|
| 79 | + |
| 80 | +
|
| 81 | +## 2、I/O 复用 |
| 82 | +
|
| 83 | +select/poll/epoll 都是 I/O 多路复用的具体实现,select 出现的最早,之后是 poll,再是 epoll。 |
| 84 | +
|
| 85 | +### 2.1select |
| 86 | +
|
| 87 | +```text |
| 88 | +int select( |
| 89 | +int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, |
| 90 | +struct timeval *timeout); |
| 91 | +``` |
| 92 | + |
| 93 | +select 允许应用程序监视一组文件描述符,等待一个或者多个描述符成为就绪状态,从而完成 I/O 操作。 |
| 94 | + |
| 95 | +- fd_set 使用数组实现,数组大小使用 FD_SETSIZE 定义,所以只能监听少于 FD_SETSIZE 数量的描述符。有三种类型的描述符类型:readset、writeset、exceptset,分别对应读、写、异常条件的描述符集合。 |
| 96 | +- timeout 为超时参数,调用 select 会一直阻塞直到有描述符的事件到达或者等待的时间超过 timeout。 |
| 97 | +- 成功调用返回结果大于 0,出错返回结果为 -1,超时返回结果为 0。 |
| 98 | + |
| 99 | +```cpp |
| 100 | +fd_set fd_in, fd_out; |
| 101 | +struct timeval tv; |
| 102 | + |
| 103 | +// Reset the sets |
| 104 | +FD_ZERO( &fd_in ); |
| 105 | +FD_ZERO( &fd_out ); |
| 106 | + |
| 107 | +// Monitor sock1 for input events |
| 108 | +FD_SET( sock1, &fd_in ); |
| 109 | + |
| 110 | +// Monitor sock2 for output events |
| 111 | +FD_SET( sock2, &fd_out ); |
| 112 | + |
| 113 | +// Find out which socket has the largest numeric value as select requires it |
| 114 | +int largest_sock = sock1 > sock2 ? sock1 : sock2; |
| 115 | + |
| 116 | +// Wait up to 10 seconds |
| 117 | +tv.tv_sec = 10; |
| 118 | +tv.tv_usec = 0; |
| 119 | + |
| 120 | +// Call the select |
| 121 | +int ret = select( largest_sock + 1, &fd_in, &fd_out, NULL, &tv ); |
| 122 | + |
| 123 | +// Check if select actually succeed |
| 124 | +if ( ret == -1 ) |
| 125 | + // report error and abort |
| 126 | +else if ( ret == 0 ) |
| 127 | + // timeout; no event detected |
| 128 | +else |
| 129 | +{ |
| 130 | + if ( FD_ISSET( sock1, &fd_in ) ) |
| 131 | + // input event on sock1 |
| 132 | + |
| 133 | + if ( FD_ISSET( sock2, &fd_out ) ) |
| 134 | + // output event on sock2 |
| 135 | +} |
| 136 | +``` |
| 137 | +
|
| 138 | +### 2.2poll |
| 139 | +
|
| 140 | +```cpp |
| 141 | +int poll(struct pollfd *fds, unsigned int nfds, int timeout); |
| 142 | +``` |
| 143 | + |
| 144 | +poll 的功能与 select 类似,也是等待一组描述符中的一个成为就绪状态。 |
| 145 | + |
| 146 | +poll 中的描述符是 pollfd 类型的数组,pollfd 的定义如下: |
| 147 | + |
| 148 | +```cpp |
| 149 | +struct pollfd { |
| 150 | + int fd; /* file descriptor */ |
| 151 | + short events; /* requested events */ |
| 152 | + short revents; /* returned events */ |
| 153 | + }; |
| 154 | +``` |
| 155 | +
|
| 156 | +
|
| 157 | +
|
| 158 | +```cpp |
| 159 | +// The structure for two events |
| 160 | +struct pollfd fds[2]; |
| 161 | +
|
| 162 | +// Monitor sock1 for input |
| 163 | +fds[0].fd = sock1; |
| 164 | +fds[0].events = POLLIN; |
| 165 | +
|
| 166 | +// Monitor sock2 for output |
| 167 | +fds[1].fd = sock2; |
| 168 | +fds[1].events = POLLOUT; |
| 169 | +
|
| 170 | +// Wait 10 seconds |
| 171 | +int ret = poll( &fds, 2, 10000 ); |
| 172 | +// Check if poll actually succeed |
| 173 | +if ( ret == -1 ) |
| 174 | + // report error and abort |
| 175 | +else if ( ret == 0 ) |
| 176 | + // timeout; no event detected |
| 177 | +else |
| 178 | +{ |
| 179 | + // If we detect the event, zero it out so we can reuse the structure |
| 180 | + if ( fds[0].revents & POLLIN ) |
| 181 | + fds[0].revents = 0; |
| 182 | + // input event on sock1 |
| 183 | +
|
| 184 | + if ( fds[1].revents & POLLOUT ) |
| 185 | + fds[1].revents = 0; |
| 186 | + // output event on sock2 |
| 187 | +} |
| 188 | +``` |
| 189 | + |
| 190 | +### 2.3比较 |
| 191 | + |
| 192 | +**1. 功能** |
| 193 | + |
| 194 | +select 和 poll 的功能基本相同,不过在一些实现细节上有所不同。 |
| 195 | + |
| 196 | +- select 会修改描述符,而 poll 不会; |
| 197 | +- select 的描述符类型使用数组实现,FD_SETSIZE 大小默认为 1024,因此默认只能监听少于 1024 个描述符。如果要监听更多描述符的话,需要修改 FD_SETSIZE 之后重新编译;而 poll 没有描述符数量的限制; |
| 198 | +- poll 提供了更多的事件类型,并且对描述符的重复利用上比 select 高。 |
| 199 | +- 如果一个线程对某个描述符调用了 select 或者 poll,另一个线程关闭了该描述符,会导致调用结果不确定。 |
| 200 | + |
| 201 | +**2. 速度** |
| 202 | + |
| 203 | +select 和 poll 速度都比较慢,每次调用都需要将全部描述符从应用进程缓冲区复制到内核缓冲区。 |
| 204 | + |
| 205 | +**3. 可移植性** |
| 206 | + |
| 207 | +几乎所有的系统都支持 select,但是只有比较新的系统支持 poll。 |
| 208 | + |
| 209 | +### 2.4epoll |
| 210 | + |
| 211 | +```cpp |
| 212 | +int epoll_create(int size); |
| 213 | +int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event); |
| 214 | +int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout); |
| 215 | +``` |
| 216 | +
|
| 217 | +
|
| 218 | +
|
| 219 | +epoll_ctl() 用于向内核注册新的描述符或者是改变某个文件描述符的状态。已注册的描述符在内核中会被维护在一棵红黑树上,通过回调函数内核会将 I/O 准备好的描述符加入到一个链表中管理,进程调用 epoll_wait() 便可以得到事件完成的描述符。 |
| 220 | +
|
| 221 | +从上面的描述可以看出,epoll 只需要将描述符从进程缓冲区向内核缓冲区拷贝一次,并且进程不需要通过轮询来获得事件完成的描述符。 |
| 222 | +
|
| 223 | +epoll 仅适用于 Linux OS。 |
| 224 | +
|
| 225 | +epoll 比 select 和 poll 更加灵活而且没有描述符数量限制。 |
| 226 | +
|
| 227 | +epoll 对多线程编程更有友好,一个线程调用了 epoll_wait() 另一个线程关闭了同一个描述符也不会产生像 select 和 poll 的不确定情况。 |
| 228 | +
|
| 229 | +```cpp |
| 230 | +// Create the epoll descriptor. Only one is needed per app, and is used to monitor all sockets. |
| 231 | +// The function argument is ignored (it was not before, but now it is), so put your favorite number here |
| 232 | +int pollingfd = epoll_create( 0xCAFE ); |
| 233 | +
|
| 234 | +if ( pollingfd < 0 ) |
| 235 | + // report error |
| 236 | +
|
| 237 | +// Initialize the epoll structure in case more members are added in future |
| 238 | +struct epoll_event ev = { 0 }; |
| 239 | +
|
| 240 | +// Associate the connection class instance with the event. You can associate anything |
| 241 | +// you want, epoll does not use this information. We store a connection class pointer, pConnection1 |
| 242 | +ev.data.ptr = pConnection1; |
| 243 | +
|
| 244 | +// Monitor for input, and do not automatically rearm the descriptor after the event |
| 245 | +ev.events = EPOLLIN | EPOLLONESHOT; |
| 246 | +// Add the descriptor into the monitoring list. We can do it even if another thread is |
| 247 | +// waiting in epoll_wait - the descriptor will be properly added |
| 248 | +if ( epoll_ctl( epollfd, EPOLL_CTL_ADD, pConnection1->getSocket(), &ev ) != 0 ) |
| 249 | + // report error |
| 250 | +
|
| 251 | +// Wait for up to 20 events (assuming we have added maybe 200 sockets before that it may happen) |
| 252 | +struct epoll_event pevents[ 20 ]; |
| 253 | +
|
| 254 | +// Wait for 10 seconds, and retrieve less than 20 epoll_event and store them into epoll_event array |
| 255 | +int ready = epoll_wait( pollingfd, pevents, 20, 10000 ); |
| 256 | +// Check if epoll actually succeed |
| 257 | +if ( ret == -1 ) |
| 258 | + // report error and abort |
| 259 | +else if ( ret == 0 ) |
| 260 | + // timeout; no event detected |
| 261 | +else |
| 262 | +{ |
| 263 | + // Check if any events detected |
| 264 | + for ( int i = 0; i < ready; i++ ) |
| 265 | + { |
| 266 | + if ( pevents[i].events & EPOLLIN ) |
| 267 | + { |
| 268 | + // Get back our connection pointer |
| 269 | + Connection * c = (Connection*) pevents[i].data.ptr; |
| 270 | + c->handleReadEvent(); |
| 271 | + } |
| 272 | + } |
| 273 | +} |
| 274 | +``` |
| 275 | + |
| 276 | + |
| 277 | + |
| 278 | +### 2.5工作模式 |
| 279 | + |
| 280 | +epoll 的描述符事件有两种触发模式:LT(level trigger)和 ET(edge trigger)。 |
| 281 | + |
| 282 | +**1. LT 模式** |
| 283 | + |
| 284 | +当 epoll_wait() 检测到描述符事件到达时,将此事件通知进程,进程可以不立即处理该事件,下次调用 epoll_wait() 会再次通知进程。是默认的一种模式,并且同时支持 Blocking 和 No-Blocking。 |
| 285 | + |
| 286 | +**2. ET 模式** |
| 287 | + |
| 288 | +和 LT 模式不同的是,通知之后进程必须立即处理事件,下次再调用 epoll_wait() 时不会再得到事件到达的通知。 |
| 289 | + |
| 290 | +很大程度上减少了 epoll 事件被重复触发的次数,因此效率要比 LT 模式高。只支持 No-Blocking,以避免由于一个文件句柄的阻塞读/阻塞写操作把处理多个文件描述符的任务饿死。 |
| 291 | + |
| 292 | +### 2.6应用场景 |
| 293 | + |
| 294 | +很容易产生一种错觉认为只要用 epoll 就可以了,select 和 poll 都已经过时了,其实它们都有各自的使用场景。 |
| 295 | + |
| 296 | +**select 应用场景** |
| 297 | + |
| 298 | +select 的 timeout 参数精度为微秒,而 poll 和 epoll 为毫秒,因此 select 更加适用于实时性要求比较高的场景,比如核反应堆的控制。 |
| 299 | + |
| 300 | +select 可移植性更好,几乎被所有主流平台所支持。 |
| 301 | + |
| 302 | +**poll 应用场景** |
| 303 | + |
| 304 | +poll 没有最大描述符数量的限制,如果平台支持并且对实时性要求不高,应该使用 poll 而不是 select。 |
| 305 | + |
| 306 | +**epoll 应用场景** |
| 307 | + |
| 308 | +只需要运行在 Linux 平台上,有大量的描述符需要同时轮询,并且这些连接最好是长连接。 |
| 309 | + |
| 310 | +需要同时监控小于 1000 个描述符,就没有必要使用 epoll,因为这个应用场景下并不能体现 epoll 的优势。 |
| 311 | + |
| 312 | +需要监控的描述符状态变化多,而且都是非常短暂的,也没有必要使用 epoll。因为 epoll 中的所有描述符都存储在内核中,造成每次需要对描述符的状态改变都需要通过 epoll_ctl() 进行系统调用,频繁系统调用降低效率。并且 epoll 的描述符存储在内核,不容易调试。 |
| 313 | + |
| 314 | +---- |
| 315 | + |
| 316 | +版权声明:本文为知乎博主「玩转Linux内核」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 |
| 317 | +原文链接:https://zhuanlan.zhihu.com/p/477292559 |
0 commit comments