How to Close a Non-Blocking Socket

How to close a non-blocking socket?


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.

Closing a UDP Socket when using Non-Blocking IO


Is there any issue associated with closing the file descriptor as soon
as the call to sendto() has completed given that it's non-blocking?

No problems there -- once sendto() has returned (with a non-error return value), your data has been copied into a system buffer and can be considered "sent". Closing the socket will not prevent the data from going out.

I'm also interested in any thread-safety considerations with doing the
above in multiple threads concurrently?

No problems there either -- since there is no data-sharing across threads, there are no race conditions possible.



Related Topics



Leave a reply



Submit