Right now I've got a simple TCP server/client. I have it set up so that whenever a client connects it gets forked() and the connection itself is put into an infinite loop so that the connection stays open. The server is receiving information from the client, I have a check to make sure that the number of bytes received is > 0. That has been working well so far in determining if the client has disconnected. But if the server disconnects the client will shut down too but no errno gets set. How can I check to make sure the server is still connected?
+1
A:
When the other end disconnects, the socket will become readable (a read on socket will not block) and the read()
will return 0
. That's the usual way disconnection is detected (it sounds like you're doing this on the server side already).
If you're blocked in a write()
or try to write
on a socket closed by the other end, your process will recieve a SIGPIPE
signal and write
will return -1
with errno
set to EPIPE
.
The default action for SIGPIPE
is to terminate the process, so if you haven't changed that, your client will just die when it tries to write to a server that's gone away.
caf
2009-09-10 22:15:21
Just before I read this answer I remembered to run it through gdb and saw it was sigpipe. I'll give you credit where credit is due though. Thanks!
whatWhat
2009-09-10 23:02:16