Under Linux, can recv ever return 0 on UDP?

前端 未结 2 602
余生分开走
余生分开走 2021-01-11 09:31

I\'m just cleaning up some code we wrote a while back and noticed that for a udp socket, 0 is being treated as the connection closed.

I\'m quite sure this was the re

2条回答
  •  温柔的废话
    2021-01-11 10:01

    In Linux there are two reasons that recvfrom on a UDP socket could return zero:

    1) a zero-length datagram was received, or 2) shutdown was called on the socket

    The second behavior is useful because it allows you to unblock a thread that is waiting on the socket. However, there is no way for the caller of recvfrom to know whether the socket was shut down or whether a zero-length datagram was received. For this you need some other way to signal to the thread that the socket was shut down, for example using a shared variable.

    The second behavior also seems to contradict the recv(2) man page, which says this:

    When  a  stream socket peer has performed an orderly shutdown, the return 
    value will be 0 (the traditional "end-of-file" return).
    

    Clearly, it also occurs for UDP sockets, which are not stream sockets.

提交回复
热议问题