【问题标题】:How does the Linux kernel remove a closed fd from the epoll interest list?Linux内核如何从epoll兴趣列表中移除一个已关闭的fd?
【发布时间】:2021-10-08 14:22:03
【问题描述】:

我正在尝试与epoll 一起玩,其中有一部分让我有点困惑。因此,来自 epoll 的手册页:

 6.  Will closing a file descriptor cause it to be removed from
           all epoll interest lists?

           Yes, but be aware of the following point.  A file descriptor
           is a reference to an open file description (see open(2)).
           Whenever a file descriptor is duplicated via dup(2), dup2(2),
           fcntl(2) F_DUPFD, or fork(2), a new file descriptor referring
           to the same open file description is created.  An open file
           description continues to exist until all file descriptors
           referring to it have been closed.

           A file descriptor is removed from an interest list only after
           all the file descriptors referring to the underlying open
           file description have been closed.
           ...

根据我的理解,这些例子是可能的:

Example1:

fd1 added to the interest list
dup(fd1) -> fd2
close(fd1) - not removed from interest list because the underlying file is still open
event for the file -> epoll signals fd1

Example2:
fd1 added to the interest list
dup(fd1) -> fd2
close(fd1) - not removed from interest list because the underlying file is still open
another file open -> this gets fd1
event for the first file -> epoll signals fd1 (for me this looks like it should not happen)

我的第一个问题是我的理解是否正确。

我的问题的第二部分是指 Linux 管理从 epoll 兴趣列表中静默删除的方式。那么,当你调用close(fd) 并且fd 在epoll 的一个或多个兴趣列表中时,内核如何知道该fd 在哪些兴趣列表中呢?这些数据是否存储在底层文件结构中?我想我的问题是从 epoll 兴趣列表中静默删除 fds 是如何一步一步发生的。

【问题讨论】:

  • 对于第一部分,事件数据是任何用户空间设置的,不一定需要解释为文件描述符。
  • 对于第二部分,struct file 通过struct filef_ep 成员和@ 链接到struct epitems 列表(在“fs/eventpoll.c”中定义) 987654329@ 的fllink 成员。当最后一个对 struct file 的引用被关闭时,eventpoll_release_file 被调用(通过eventpoll_release)从其包含的兴趣列表中删除(ep_remove)列表中的每个struct epitem
  • 对于第二部分,你是对的。对于第一部分,我不确定我是否理解您的回答。
  • 对于第一部分,我的意思是当epoll_wait() 填写struct epoll_event 时,data 成员(epoll_data_t 类型)与用户代码在添加时设置的值相同将事件添加到兴趣列表(epoll_ctl()EPOLL_CTL_ADDEPOLL_CTL_MOD)。 data 成员的值需要是用户代码用来识别特定事件的值,但它不需要是文件描述符。

标签: linux linux-kernel operating-system polling epoll


【解决方案1】:

当 fd1 被删除并且 fd2 相同时,内核不会删除打开的文件描述,但会从文件描述符表中删除条目,即内核中的内部数据结构仍然保持不变,但不再与 fd1 索引关联

在内部,epoll fd 将兴趣列表保存在内核数据结构中,它了解在调用关闭兴趣列表时需要清理所有打开的文件描述。以下链接确实有更多信息。 https://unix.stackexchange.com/questions/195057/what-is-an-open-file-description

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2012-07-13
    相关资源
    最近更新 更多