1

I need some insight on socket error handling in c++ (or c). I am testing a simple client and server program like under:

 .....
 while (1) { // server keeps sending strings to client
     sprintf(jsonStr, "{ \"%d: Hello\": \"world!\" } \n", index++);
     size = send(newsockfd, jsonStr, strlen(jsonStr), 0);
     if (size == -1) {
       error("ERROR on send");
     }
     sleep(1);
 }
 .....

While client is receiving strings from server, if I kill client, server also exits without any message. Is this expected? How can I catch it instead of exiting? I tried "try" and "catch" but wasn't able to catch. With java, I get the "Broken pipe" SocketException using DataOutputStream.writeUTF(). I have tested on Mac and Linux and their results were same.

I use example codes from: https://www.bogotobogo.com/cplusplus/sockets_server_client.php

Thanks in advance.

Jae
  • 91
  • 1
  • 7

1 Answers1

0

Attempting to send on a broken socket will raise a SIGPIPE signal. The default behavior when receiving a SIGPIPE is to terminate the process (which is the behavior you are observing).

You can fix this by:

  • Ignoring the signal (works on any platform)
  • Setting the SO_NOSIGPIPE socket option (Mac/BSD only)
  • Passing the MSG_NOSIGNAL flag to send (Linux only)

send should then return -1 with errno set to EPIPE if a write is performed on a broken socket.

For further details on handling SIGPIPE, see:

Mikel Rychliski
  • 3,455
  • 5
  • 22
  • 29