Epoll 能監(jiān)聽普通文件嗎?
本文轉(zhuǎn)載自微信公眾號「Linux內(nèi)核那些事」,作者songsong001 。轉(zhuǎn)載本文請聯(lián)系Linux內(nèi)核那些事公眾號。
epoll 是 Linux 系統(tǒng)中常用的多路復(fù)用 I/O 組件,一般用于監(jiān)聽 socket 是否能夠進(jìn)行 I/O 操作。那么,epoll 能監(jiān)聽普通文件嗎?
我們先通過下面的例子來驗證一下,epoll 能不能監(jiān)聽普通文件:
- #include <stdio.h>
- #include <sys/epoll.h>
- #include <fcntl.h>
- int main()
- {
- int epfd, fd;
- struct epoll_event ev, events[2];
- int result;
- epfd = epoll_create(10);
- if (epfd < 0) {
- perror("epoll_create()");
- return -1;
- }
- fd = open("./test.txt", O_RDONLY | O_CREAT);
- if (fd < 0) {
- perror("open()");
- return -1;
- }
- 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;
- }
編譯并且運行,結(jié)果如下:
- [vagrant@localhost epoll]$ gcc epoll.c -o epoll
- [vagrant@localhost epoll]$ ./epoll
- epoll_ctl(): Operation not permitted
可以看到上面的運行結(jié)果報 Operation not permitted 的錯誤,這說明 epoll 是不能監(jiān)聽普通文件的,為什么呢?
尋根究底
我們應(yīng)該對追尋真相抱著熱衷的態(tài)度,所以必須找出 epoll 不能監(jiān)聽普通文件的原因。
因為在上面的例子中,是 epoll_ctl 函數(shù)報的錯,所以我們首先應(yīng)該從 epoll_ctl 的源碼入手,如下:
- SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
- struct epoll_event __user *, event)
- {
- int error;
- struct file *file, *tfile;
- ...
- error = -EBADF;
- file = fget(epfd); // epoll 句柄對應(yīng)的文件對象
- if (!file)
- goto error_return;
- tfile = fget(fd); // 被監(jiān)聽的文件句柄對應(yīng)的文件對象
- if (!tfile)
- goto error_fput;
- error = -EPERM; // Operation not permitted 錯誤號
- if (!tfile->f_op || !tfile->f_op->poll)
- goto error_tgt_fput;
- ...
- error_tgt_fput:
- fput(tfile);
- error_fput:
- fput(file);
- error_return:
- return error;
- }
從上面代碼可以看出,當(dāng)被監(jiān)聽的文件沒有提供 poll 接口時,就會返回 EPERM 的錯誤,這個錯誤就是 Operation not permitted 的錯誤號。
所以,出現(xiàn) Operation not permitted 的原因就是:被監(jiān)聽的文件沒有提供 poll 接口。
由于我們的文件系統(tǒng)是 ext4,所以我們來看看 ext4 文件系統(tǒng)中的文件是否提供了 poll 接口(位于文件 /fs/ext4/file.c 中):
- const struct file_operations ext4_file_operations = {
- .llseek = generic_file_llseek,
- .read = do_sync_read,
- .write = do_sync_write,
- .aio_read = generic_file_aio_read,
- .aio_write = ext4_file_write,
- .unlocked_ioctl = ext4_ioctl,
- .mmap = ext4_file_mmap,
- .open = ext4_file_open,
- .release = ext4_release_file,
- .fsync = ext4_sync_file,
- .splice_read = generic_file_splice_read,
- .splice_write = generic_file_splice_write,
- ;
ext4 文件的文件操作函數(shù)集被設(shè)置為 ext4_file_operations(也說就是:file->f_op = ext4_file_operations),從上面代碼可以看出,ext4_file_operations 并沒有提供 poll 接口。所以,當(dāng)調(diào)用 epoll_ctl 把文件添加到 epoll 中進(jìn)行監(jiān)聽時,就會返回 Operation not permitted 的錯誤。
從上面的分析可知,當(dāng)文件系統(tǒng)提供 poll 接口時,就可以把文件添加到 epoll 中進(jìn)行監(jiān)聽。