Epoll 能监听普通文件吗?

2025-05-27 0 77

Epoll 能监听普通文件吗?

epollLinux 系统中常用的多路复用 I/O 组件,一般用于监听 socket 是否能够进行 I/O 操作。那么,epoll监听普通文件吗?

我们先通过下面的例子来验证一下,epoll 能不能监听普通文件:

  1. #include<stdio.h>
  2. #include<sys/epoll.h>
  3. #include<fcntl.h>
  4. intmain()
  5. {
  6. intepfd,fd;
  7. structepoll_eventev,events[2];
  8. intresult;
  9. epfd=epoll_create(10);
  10. if(epfd<0){
  11. perror("epoll_create()");
  12. return-1;
  13. }
  14. fd=open("./test.txt",O_RDONLY|O_CREAT);
  15. if(fd<0){
  16. perror("open()");
  17. return-1;
  18. }
  19. ev.events=EPOLLIN;
  20. result=epoll_ctl(epfd,EPOLL_CTL_ADD,fd,&ev);
  21. if(result<0){
  22. perror("epoll_ctl()");
  23. return-1;
  24. }
  25. epoll_wait(epfd,events,2,-1);
  26. return0;
  27. }

编译并且运行,结果如下:

  1. [vagrant@localhostepoll]$gccepoll.c-oepoll
  2. [vagrant@localhostepoll]$./epoll
  3. epoll_ctl():Operationnotpermitted

可以看到上面的运行结果报 Operation not permitted 的错误,这说明 epoll 是不能监听普通文件的,为什么呢?

寻根究底

我们应该对追寻真相抱着热衷的态度,所以必须找出 epoll 不能监听普通文件的原因。

因为在上面的例子中,是 epoll_ctl 函数报的错,所以我们首先应该从 epoll_ctl 的源码入手,如下:

  1. SYSCALL_DEFINE4(epoll_ctl,int,epfd,int,op,int,fd,
  2. structepoll_event__user*,event)
  3. {
  4. interror;
  5. structfile*file,*tfile;
  6. error=-EBADF;
  7. file=fget(epfd);//epoll句柄对应的文件对象
  8. if(!file)
  9. gotoerror_return;
  10. tfile=fget(fd);//被监听的文件句柄对应的文件对象
  11. if(!tfile)
  12. gotoerror_fput;
  13. error=-EPERM;//Operationnotpermitted错误号
  14. if(!tfile->f_op||!tfile->f_op->poll)
  15. gotoerror_tgt_fput;
  16. error_tgt_fput:
  17. fput(tfile);
  18. error_fput:
  19. fput(file);
  20. error_return:
  21. returnerror;
  22. }

从上面代码可以看出,当被监听的文件没有提供 poll 接口时,就会返回 EPERM 的错误,这个错误就是 Operation not permitted 的错误号。

所以,出现 Operation not permitted 的原因就是:被监听的文件没有提供 poll 接口。

由于我们的文件系统是 ext4,所以我们来看看 ext4 文件系统中的文件是否提供了 poll 接口(位于文件 /fs/ext4/file.c 中):

  1. conststructfile_operationsext4_file_operations={
  2. .llseek=generic_file_llseek,
  3. .read=do_sync_read,
  4. .write=do_sync_write,
  5. .aio_read=generic_file_aio_read,
  6. .aio_write=ext4_file_write,
  7. .unlocked_ioctl=ext4_ioctl,
  8. .mmap=ext4_file_mmap,
  9. .open=ext4_file_open,
  10. .release=ext4_release_file,
  11. .fsync=ext4_sync_file,
  12. .splice_read=generic_file_splice_read,
  13. .splice_write=generic_file_splice_write,
  14. ;

ext4 文件的文件操作函数集被设置为 ext4_file_operations(也说就是:file->f_op = ext4_file_operations),从上面代码可以看出,ext4_file_operations 并没有提供 poll 接口。所以,当调用 epoll_ctl 把文件添加到 epoll 中进行监听时,就会返回 Operation not permitted 的错误。

从上面的分析可知,当文件系统提供 poll 接口时,就可以把文件添加到 epoll 中进行监听

原文链接:https://mp.weixin.qq.com/s/HGeHm30pilIFaik2Hi9fBg

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Epoll 能监听普通文件吗? https://www.kuaiidc.com/62855.html

相关文章

发表评论
暂无评论