Linux 在关闭套接字之前是否需要从 epoll 中注销套接字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8707601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:53:04  来源:igfitidea点击:

Is it necessary to deregister a socket from epoll before closing it?

linuxsocketsepoll

提问by selbie

Assume the following code where "sock" is a handle to TCP socket that was previously registered with an epoll file descriptor designated by epfd.

假设以下代码,其中“sock”是 TCP 套接字的句柄,该套接字先前已使用 epfd 指定的 epoll 文件描述符注册。

epoll_ctl(epfd, EPOLL_CTL_DEL, sock, &ev);
close(sock);

Is it still necessary to call epoll_ctl if the socket is going to get subsequently closed anyway? Or does the socket get implicitly deregistered as a result of closing it?

如果套接字随后要关闭,是否仍然需要调用 epoll_ctl ?或者套接字是否因关闭而被隐式取消注册?

采纳答案by Frédéric Hamidi

From the man page:

手册页

Q6Will closing a file descriptor cause it to be removed from all epoll sets automatically?

A6Yes, but be aware of the following point. A file descriptor is a reference to an open file description (see open(2)). Whenever a 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 epollset only after all the file descriptors referring to the underlying open file description have been closed (or before if the descriptor is explicitly removed using epoll_ctl(2) EPOLL_CTL_DEL). This means that even after a file descriptor that is part of an epollset has been closed, events may be reported for that file descriptor if other file descriptors referring to the same underlying file description remain open.

Q6关闭文件描述符会导致它自动从所有 epoll 集中删除吗?

A6是的,但请注意以下几点。文件描述符是对打开文件描述的引用(参见open(2))。每当通过dup(2)、dup2(2)、fcntl(2)F_DUPFDfork(2)复制描述符时,都会创建一个引用相同打开文件描述的新文件描述符。一个打开的文件描述会一直存在,直到所有引用它的文件描述符都被关闭。epoll仅在所有引用底层打开文件描述的文件描述符都已关闭后(或在使用epoll_ctl(2)显式删除描述符之前),才从集合中删除文件描述符EPOLL_CTL_DEL。这意味着即使在作为文件描述符的一部分之后epollset 已关闭,如果引用相同底层文件描述的其他文件描述符保持打开状态,则可能会报告该文件描述符的事件。