0

I'm having issues trying to close my server socket in c++. When I start my application, I have my main thread and I create another one that configure, bind and accept connections.

My problem comes from the fact I can't close the socket fd from another thread than the one which has created the fd.

I tried creating a loop like below:

while (!_stopRequested) {
    client_session = accept(_session, reinterpret_cast<socket_t *>(&client_insocket), &clientsocksize);
    if (client_session == SOCKET_ERROR) {
        fprintf(stderr, "Socket accept error\n");
        continue;
    }
    printf("TODO clients holding, data serialization");
}

_stopRequested is set to true from the main thread when I want to exit the loop and then close the sockets but it has no effect. It's due of the fact that the loop is blocking on accept. Is there a way to make accept non-blocking one time? then the loop will be broken as expected, and I will be able to close the socket from the thread holding the loop.

Potential Solution

I was about to handle a SIGINT on the server-socket thread. By calling pthread_kill(ssocket_thread, SIGINT), I should close the server socket from the handler and then pthread_terminate(). But this way requires to make a static variable and static function, Im wondering if an easier solution exists..

Alpha bot
  • 13
  • 2
  • If you make the socket non-blocking, you can `poll()` it for writing (indicating that there's a new connection that can be `accept`()ed), together with some other file descriptor that would be used to signal termination. A plain flag, like this, is not going to work reliably. – Sam Varshavchik Apr 19 '18 at 01:15
  • the duplicate topic didnt help, I have no clue how to do it since there is no explanation on google.. IS this possible to provide an example or remove the duplicate.. – Alpha bot Apr 19 '18 at 01:24

0 Answers0