在什么情况下在前台或后台关闭/关闭?

时间:2016-10-04 00:40:55

标签: linux sockets epoll

我正在使用以下方法在服务器端的套接字上进行中断关闭:

struct linger so_linger;
so_linger.l_onoff = 1;
so_linger.l_linger = 0;
setsockopt(s, SOL_SOCKET, SO_LINGER, &so_linger, socklen_t)sizeof(so_linger));

shutdown(s, SHUT_WR);
close(s);

s是我正在关闭的套接字。

它可以工作,但有时我遇到了一个问题,它似乎影响了一些服务器,而不是其他服务器。有些在Ubuntu上运行,有些在CoreOS上运行。它在CoreOS上运行良好。

在Ubuntu上,我从epoll_wait收到一个与套接字相关的事件,尽管已经关闭了。

我认为这会立即发生。但是,如果您使用非阻塞I / O,我认为情况可能并非如此。

它实质上意味着我在epoll_wait中获取了一个ev.data.ptr值设置的事件,该值指向已经被破坏的东西。

所以,问题是,这是真的吗?半关闭不会从epoll中删除事件描述符,关闭不会与非阻塞i / o同步?

因此,如果我不再需要事件,我实际上应该使用EPOLL_CTL_DEL手动删除描述符?

1 个答案:

答案 0 :(得分:0)

关闭套接字确实会从epoll集中清除它。但有一点需要注意。参考epoll man page

> Q6  Will closing a file descriptor cause it to be removed from all
           epoll sets automatically?

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

因此,在调用close的套接字上可能会报告事件。不确定您的测试是否可以在某些平台上正常运行。当然,我不认为它与异步I / O有关。