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..