[Python] Why does closing a client socket connection raise two epoll events?

Discussão em 'Python' iniciado por Stack, Dezembro 1, 2024.

  1. Stack

    Stack Membro Participativo

    It seems that the epoll system will raise a pair of events if a client socket disconnects using the close function call.

    I am experimenting with a short server and client implementation in Python.

    On the client side, when the client calls

    socket.close()


    a pair of events are raised on the server side.

    Those events correspond to EPOLLIN and EPOLLHUP.

    Why are both events raised, rather than a single event EPOLLHUP?

    This question may seem trivial or unimportant, but it is not because if more than one event can be raised simultaniously, the logic to handle such events becomes complex.

    There are approximatly 10 different types of event in the bitmask.


    Presumably some of these are independent. However, in this case, it appears to be the case that EPOLLHUP implies EPOLLIN.

    One possible way to write the logic to handle epoll events would be to have a series of if statements which check to see if a particular bit is set.

    Here's what that would look like:

    if event & select.EPOLLIN:

    if event & select.EPOLLHUP:

    if event & select.EPOLLOUT:

    ...


    However, the ordering of these statements is important. If we check for EPOLLIN first, and find that there are zero bytes of data to read, this suggests the client has disconnected.

    If we handle that logic in the first if statement, then our code will break, because the second if statement will also evaluate as true.

    Another possibility might be to be more rigid with the logic. Here's an example:

    if event == (select.EPOLLIN & select.EPOLLHUP):

    if event == (select.EPOLLIN):

    ...


    This is likely to be quite fragile, and it is unrealistic to try and cover all possible combinations.

    I hope the question makes sense. To review: Why a pair of events at once, especially in this case where they both appear to have the same meaning. (Client has disconnected.)

    Continue reading...

Compartilhe esta Página