What is poll?
poll是linux内核的一个系统调用,实现I/O多路复用,可以同时等待多个文件描述符的IO事件。
简单的场景,一个app需要同时监听键盘的输入和鼠标的输入,我们可以用两个线程来做,但是有一种更简单高效的办法就是I/O多路复用,即用一个线程来监听多个文件描述符的输入事件。常用的技术有poll, select, epoll等,他们有着各自使用的场景,这里我们只介绍poll。
#include <poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};
poll 需要传入文件描述符数组指针地址和个数,超时时间。
poll会一直阻塞,直到以下的3中情况才会结束:
任意一个文件描述符有I/O事件;
被信号中断;
或者超时
后面我们提供了例子,查看这几种中断的场景。
How to use?
例子1,正常的文件描述符返回
在https://man7.org/linux/man-pages/man2/poll.2.html中给出了一个简单的例子,可以实现poll多个fds,一旦其中一个fd ready,poll就会返回。
/* poll_input.c
Licensed under GNU General Public License v2 or later.
*/
#include <poll.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
int
main(int argc, char *argv[])
{
int nfds, num_open_fds;
struct pollfd *pfds;
if (argc < 2) {
fprintf(stderr, "Usage: %s file...\n", argv[0]);
exit(EXIT_FAILURE);
}
num_open_fds = nfds = argc - 1;
pfds = calloc(nfds, sizeof(struct pollfd));
if (pfds == NULL)
errExit("malloc");
/* Open each file on command line, and add it 'pfds' array */
for (int j = 0; j < nfds; j++) {
pfds[j