0

I'm working on a C++ TCP server - multi client program. The problem is why the return value of write() may be a number greater than 0 even a client has been disconnected (in this case, I test with localhost and press Ctrl+C so one of the client programs ends, but it forces the main program to close).

There are some questions: 1. How to detect if write to client failed 2. Why the return value of write() is not <= 0 when it failed? 3. How to prevent the server program force close caused by a client program closed?

SergeyA
  • 61,605
  • 5
  • 78
  • 137
ZZZ
  • 1,415
  • 5
  • 16
  • 29

1 Answers1

0

This is inherent nature of TCP protocol. Succeeding in write() does not mean the message was read (or even reached) the server. Without going into too much details on TCP stack implementation, just accept this as a fact of life.

If you want to make sure the message has been read, you'd have to introduce your own acknowlegement protocol on top. Lack of acknowlegement would mean the message was lost.

Answering question on crash when writing to closed socket:

Application terminates because writing to closed socket by default causes SIGPIPE signal. There are two ways to prevent this:

  • Set SIGPIPE handler to SIG_IGN and deal with write() errors.
  • Depending on your OS, either set SO_NOSIGPIPE on the socket using setsockopt(), or use MSG_NOSIGNAL as a flag to your send().
SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • But my problem is the server program terminates after it failed to read from the client that has been closed. Is there a way to prevent the server program terminated? – ZZZ Dec 02 '15 at 15:38
  • @ZZZ, answered in the answer :) – SergeyA Dec 02 '15 at 16:21