一般使用 poll 检测 socket 或标准输入时,只要指定 POLLIN 标志位,就可以检测是否有数据到达,或者连接断开:
1 struct pollfd fds[3]; 2 fds[0].fd = STDIN_FILENO; 3 fds[0].events = POLLIN; 4 fds[1].fd = sock_fd; 5 fds[1].events = POLLIN; 6 fds[2].fd = pipe_fd; 7 fds[2].events = POLLIN; 8 ret = poll(fds, 3, -1); 9 if (ret > 0) { 10 if (fds[0].revents & POLLIN) { 11 // handle stdin 12 ... 13 } 14 if (fds[1].revents & POLLIN) { 15 // handle socket input 16 ... 17 } 18 if (fds[2].revents & POLLIN) { 19 // handle pipe input 20 ... 21 } 22 }
当 read 结果返回 0 时表示相应连接断开。
而对于 pipe,只检测POLLIN是感知不到管道断开的,当管道断开时,会在revents设置POLLHUP,必需额外检测此标志位:
1 if (pfd[2].revents & POLLHUP) { 2 // handle pipe break 3 ... 4 }