close() socket directly after send(): unsafe?

后端 未结 1 830
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 00:46

Is it wise/safe to close() a socket directly after the last send()?

I know that TCP is supposed to try to deliver all remaining data in the

相关标签:
1条回答
  • 2020-12-08 01:45

    I've been reading the The ultimate SO_LINGER page, or: why is my tcp not reliable blog post a lot. I recommend you read it too. It discusses edge cases of large data transfers with regards to TCP sockets.

    I'm not the expert at SO_LINGER, but on my server code (still in active development) I do the following:

    1. After the last byte is sent via send(), I call shutdown(sock, SHUT_WR) to trigger a FIN to be sent.

    2. Then wait for a subsequent recv() call on that socket to return 0 (or recv returns -1 and errno is anything other that EAGAIN/EWOULDBLOCK).

    3. Then the server does a close() on the socket.

    The assumption is that the client will close his socket first after it has received all the bytes of the response.

    But I do have a timeout enforced between the final send() and when recv() indicates EOF. If the client never closes his end of the connection, the server will give up waiting and close the connection anyway. I'm at 45-90 seconds for this timeout.

    All of my sockets are non-blocking and I use poll/epoll to be notified of connection events as a hint to see if it's time to try calling recv() or send() again.

    0 讨论(0)
提交回复
热议问题