Sagar
Sagar

Reputation: 9503

Would the socket descriptor change if a client closed the connection?

We have a server with a limited on the number of incoming connections it can accept. We have multiple clients connecting to the server at various intervals, for various different reasons.

At least one of the functions of the server requires it to process the client's request and reply back on the same socket. However:

I have code similar to the one below, that checks the socket descriptor.

if (connect_desc > 0)
{
    if (write(connect_desc, buffer, sizeof(buffer)) < 0)
    {
        printf("write error\n");
    }
}
else
    printf("connect_desc < 0\n");

My question is:

If the socket is closed by the client, would the socket descriptor change in value on the server? If not, is there any way to catch that in my code?

I'm not seeing that last print out.

Upvotes: 0

Views: 1452

Answers (2)

user207421
user207421

Reputation: 311048

Q. Will the file descriptor change?

Not unless:

  1. It is documented somewhere you can cite.
  2. The operating system magically knows about the disconnection.
  3. The operating system magically knows where in your application the FD is stored, including all the copies.
  4. The operating system wants to magically make it impossible for you to close the socket yourself.

None of these is true. The question doesn't even make sense.

Q. How can I check the status of my connection.

There isn't, by design, any such thing as the status of a TCP connection. The only way you can detect whether it has failed is by trying to use it.

Upvotes: 0

paulsm4
paulsm4

Reputation: 121869

Q: Will the descriptor change?

A: No

Q: How can I check the status of my connection?

A: One way is simply to try writing to the socket, and check the error status.

STRONG RECOMMENDATION:

Upvotes: 2

Related Questions