Suppose, I have a connected socket after writing this code..
if ((sd = accept(socket_d, (struct sockaddr *)&client_addr, &alen)) < 0)
{
perror(\"a
After accepting the connection, your recv()
on the socket will return 0 or -1 in special cases.
Excerpt from recv(3) man page:
Upon successful completion, recv() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.
So, if your client exited gracefully, you will get 0 from recv()
at some point. If the connection was somehow lost, you may also get -1 and checking for appropriate errno would tell you if the connection was lost of some other error occured. See more details at recv(3) man page.
Edit:
I see that you are using read()
. Still, the same rules as with recv()
apply.
Your server can also fail when trying to write()
to your clients. If your client disconnects write()
will return -1 and the errno would probably be set to EPIPE
. Also, SIGPIPE
signal will be send to you process and kill him if you do not block/ignore this signal. And you don't as I see and this is why your server terminates when client presses Ctrl-C. Ctrl-C terminates client, therefore closes client socket and makes your server's write()
fail.
See mark4o's answer for nice detailed explanation of what else might go wrong.