Calling close() on a non blocking socket from within an io watcher

Marc Lehmann schmorp at
Sat Aug 8 14:39:41 CEST 2009

On Sat, Aug 08, 2009 at 02:17:45AM +0200, Graham Leggett <minfrin at> wrote:
> when set, means "shut the connection down when you have finished writing
> all buffered data to the socket".
> The problem that I have is that I cannot seem to figure out the "right"
> way to close the socket at this point.

the correct solution is to use a protocol with handshake.

> If I call shutdown()/close() immediately after the write(), the data in
> the send buffer is lost, and the other side loses the last bit of data.
> This is because close() dumps everything in the sending buffer that is

that would be a bug in your operating system - the bsd sockets api
requires lingering to be enabled by default, meaning the data is not lost
(unless the other side times out).

the correct solution is to fix your protocol, however.

> as yet unsent. Because the write() is non blocking, the close is issued
> too early. Fair enough, this is the wrong way to do it.

yes, close does not dump the data, regardless of whether write is blocking or
not. the kernel also buffers, regardless of whether the write is blocking or

blocking vs. non-blocking is not the issue, the behaviour is exactly the

> Does anyone know the right way to do this?

yes, wait for an acknowledgement from the other side. tcp requires this,
regardless of blocking mode.

                The choice of a       Deliantra, the free code+content MORPG
      -----==-     _GNU_    
      ----==-- _       generation
      ---==---(_)__  __ ____  __      Marc Lehmann
      --==---/ / _ \/ // /\ \/ /      pcg at
      -=====/_/_//_/\_,_/ /_/\_\

More information about the libev mailing list