views:

47

answers:

4

In Socket Programming, how will a Unix thread receive a Socket CLOSE event from a client if connection is closed?

Are there any API's which will notify the unix thread about the CLOSE event received?

As in Windows we have WSAEnumNetworkEvents API which gets the event notification for a specified socket descriptor. What will be the equivalent API used in the Unix socket programing?

Please provide the help for the query.

A: 

Sorry no time for an answer, but check out Beej's Guide to Network Programming

Martin Beckett
+2  A: 

You can track the closure event when performing reading. The socket is closed when read returns 0 (talking about "Berkeley sockets" of course).

//EDIT: Use poll or select to wait for some event to occur (data arrival, socket closure ...).

adf88
oh yes, I remember a guideline now, `shutdown`the writing, read with `recv` until 0 is returned, `shutdown` the other half and `close` the socket... +1, my answer is actually offering an alternative (which I prefer) but my answer did not answer the actual question....
jdehaan
A: 

Did you think about using boost::asio, this way you can share at least the code between linux & windows. The overhead is not that big compared to naked sockets and you have the benefit of better semantics. Many parts of code from boost have flown into standard C++ so the code is of rather high quality.

This involves rewriting your software what might not be an option. On the other hand you would have a common codebase to maintain.

jdehaan
A: 

libevent will allow you receive an event when there is data on the socket or when the socket needs to be closed. More specifically, you want to setup the socket to notify you on a read event (EV_READ) and in the function callback check if the return value from recv is 0 which indicates that the socket at the other end has shutdown cleanly or -1 which indicates an error. In the first case, where the return value is 0, you want to close the socket. In the second case, where the return of -1 indicates some sort of 'error', what you do depends on the nature of the error. For example recv may return -1 and set errno to EINTR indicating that the function was interrupted, for example via a SIGUSR1 interrupt. How you handle that depends on what your application needs to do.

sashang