poll
是 Linux 系统中的一个 I/O 多路复用机制,它允许单个进程/线程处理多个文件描述符上的 I/O 事件。与 select
和 epoll
相比,poll
在某些场景下提供了更好的性能和易用性。
select
不同,poll
不受文件描述符数量的硬性限制。select
,poll
的 API 更简洁,易于使用。poll
在检查文件描述符状态时,只会返回就绪的文件描述符,减少了不必要的系统调用。poll
主要用于处理网络 I/O 和文件 I/O。以下是一个简单的 poll
示例,演示如何使用 poll
监听多个文件描述符上的读事件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/poll.h>
int main() {
struct pollfd fds[2];
int timeout = 5000; // 5秒超时
// 初始化文件描述符
fds[0].fd = STDIN_FILENO;
fds[0].events = POLLIN;
fds[1].fd = open("test.txt", O_RDONLY);
if (fds[1].fd == -1) {
perror("open");
return 1;
}
fds[1].events = POLLIN;
while (1) {
int ret = poll(fds, 2, timeout);
if (ret == -1) {
perror("poll");
break;
} else if (ret == 0) {
printf("Timeout occurred!\n");
continue;
}
for (int i = 0; i < 2; i++) {
if (fds[i].revents & POLLIN) {
char buffer[1024];
ssize_t len = read(fds[i].fd, buffer, sizeof(buffer));
if (len > 0) {
buffer[len] = '\0';
printf("Read from fd %d: %s", fds[i].fd, buffer);
}
}
}
}
close(fds[1].fd);
return 0;
}
poll
和相关系统调用的返回值进行充分检查,并妥善处理错误情况。close
函数关闭了打开的文件描述符。timeout
变量的值。poll
和 read
系统调用的返回值进行了检查,并使用 perror
函数打印错误信息。总之,poll
是一种高效的 I/O 多路复用机制,在 Linux 系统中得到了广泛应用。通过合理使用和优化,可以充分发挥其性能优势。
领取专属 10元无门槛券
手把手带您无忧上云