测试epoll能否监听普通文件。
epoll是Linux系统中常用的多路复用I/O组件,可以用来监听socket的I/O操作,但是监听的都是fd,那么打开的普通文件fd可以被监听吗?
测试代码:
//gcc epoll_file.c -o epoll_file
#include<stdio.h>
#include<sys/epoll.h>
#include<fcntl.h>
int main()
{
struct epoll_event ev, events[2];
int epfd, fd;
int result;
//创建 epoll
epfd = epoll_create(5);
if (epfd < 0)
{
perror("epoll_create()");
return -1;
}
// 打开文件
fd = open("test.txt", O_RDONLY | O_CREAT);
if (fd < 0) {
perror("open()");
return -1;
}
ev.data.fd = fd;
ev.events = EPOLLIN;
result = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
if (result < 0) {
perror("epoll_ctl()");
return -1;
}
epoll_wait(epfd, events, 2, -1);
return 0;
}
执行结果:执行报错,看来普通文件不能被epoll监听。