Alex Rivera | Logout

Why is writing a closed TCP socket worse than reading one?

Asked 2010-02-07T08:12:27.010
14

When you read a closed TCP socket you get a regular error, i.e. it either returns 0 indicating EOF or -1 and an error code in errno which can be printed with perror.

However, when you write a closed TCP socket the OS sends SIGPIPE to your app which will terminate the app if not caught.

Why is writing the closed TCP socket worse than reading it?

Edit
Report

1 Answer

7

Think of the socket as a big pipeline of data between the sending and the receiving process. Now imagine that the pipeline has a valve that is shut (the socket connection is closed).

If you're reading from the socket (trying to get something out of the pipe), there's no harm in trying to read something that isn't there; you just won't get any data out. In fact, you may, as you said, get an EOF, which is correct, as there's no more data to be read.

However, writing to this closed connection is another matter. Data won't go through, and you may wind up dropping some important communication on the floor. (You can't send water down a pipe with a closed valve; if you try, something will probably burst somewhere, or, at the very least, the back pressure will spray water all over the place.) That's why there's a more powerful tool to alert you to this condition, namely, the SIGPIPE signal.

You can always ignore or block the signal, but you do so at your own risk.

answered 2010-02-07T08:43:52.153

Your Answer