How to close a non-blocking socket?

北城余情 提交于 2020-01-10 19:44:23

问题


I believe that if we call close system call on a non-blocking socket it returns immediately, then how to handle the response? whether it is closed or not? in other words what is the behavior of the socket system call close on a non-blocking socket?


回答1:


if we call close system call on a non-blocking socket it returns immediately

The socket is always closed: the connection may still be writing to the peer. But your question embodies a fallacy: if you call close() on any socket it will return immediately. Closing and writing to a socket is asynchronous. You can control that with SO_LINGER as per the other answer, although I suspect that only applies to blocking mode. Probably you should put the socket back into blocking mode before closing with a positive SO_LINGER if that's what you need to do.




回答2:


It's not the blocking state of the socket, it's the SO_LINGER option that matters. From getsockopt(2):

SO_LINGER controls the action taken when unsent messages are queued on socket and a close(2) is performed. If the socket promises reliable delivery of data and SO_LINGER is set, the system will block the process on the close(2) attempt until it is able to transmit the data or until it decides it is unable to deliver the information (a timeout period, termed the linger interval, is specified in seconds in the setsockopt() system call when SO_LINGER is requested). If SO_LINGER is disabled and a close(2) is issued, the system will process the close in a manner that allows the process to continue as quickly as possible.

That is, with SO_LINGER enabled an error from close(2) on TCP socket would mean that kernel was not able to deliver data within linger interval (not counting other errors like invalid file descriptor, etc.). With lingering disabled - you never know. Also see The ultimate SO_LINGER page, or why is my tcp not reliable.



来源:https://stackoverflow.com/questions/6418277/how-to-close-a-non-blocking-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!