Mike
Mike

Reputation: 878

Check of socket closure

I have an application which connected to some server. It can send data synchronously (send and wait answer) and receive data asynchronously. I made 2 threads. In the first thread in the infinity loop I send data and wait answer. In the second thread I'm cathing data from server and push they in queue. But, if happened some errors when I send data (in the first thread) I have to close socket. And how can I check in the second thread that socket is closed?

Code in the second thread:

while (processing) {
  nbytes = recv(socketDesc, canFrame, sizeof(data), 0);
  if (nbytes > 0) {
    push_queue(data);
  }
  if (nbytes < 0) {
    throw "Error in read data from socket!";
  }
}

If I closed socket in the first thread in the second thread function recv does not take error. Now I use timeout, like this:

setsockopt(this->socketDesc, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
  setsockopt(this->socketDesc, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));

When error happens when I don't get answer from server (in the first thread) I set variable processing to false and after timeout expires (in function recv) loop is ended. Can I Check of socket closure at once in function recv?

Upvotes: 0

Views: 98

Answers (2)

user325117
user325117

Reputation:

Here's how you ensure that you don't close the socket while the reading thread is reading.

You have 2 shared boolean variables protected by a mutex:

bool reading = false;
bool closed = false;

All accesses to these are are preceded by locking the mutex, and succeeded by unlocking it.

The writing thread:

  1. Writes
  2. If writing fails:
    1. Sets closed to true
    2. Waits for reading to become false
    3. Closes the socket

The reading thread:

  1. Checks that closed is not true. If it isn't:
    1. Sets reading to true
    2. Reads
    3. Sets reading to false

Upvotes: 1

user325117
user325117

Reputation:

There is no timely way of determining that you have closed the socket. You need a variable shared between both threads and protected by a mutex. The first thread can set the variable if it closes the socket, and the second thread should check it before doing a recv.

Upvotes: 1

Related Questions