I am working on a program using threads to treat demands of remote clients in C++. The server will wait for clients to connect, and launch a thread doing some things.
For the server to shut down, the user must do an external interrupt Crtl+C, and the code will handle the signal (using <csignal>) in order to shut everything properly.
The waiting itself is made with a while
loop, the server waits for a connection, and launches the thread. It's during this loop that I want to handle the signal. Here it is:
std::signal(SIGINT, interruptHandler);
while(intStatus != 2){
ClientSocket client;
client.csock = accept(sock,reinterpret_cast<SOCKADDR*>(&(client.csin)),&(client.crecsize));
tArray.push_back(new pthread_t);
pthread_create(tArray.back(), NULL, session, &client);
}
std::cout<<"Waiting for Clients to exit..."<<std::endl;
for(pthread_t* thread : tArray)
pthread_join(*thread,NULL);
std::sig_atomic_t intStatus
is a global variable edited byinterruptHandler
when it's called.ClientSocket
is astruct
containing informations about the client:csoc
the socket of the clientcsin
the adress of the socketcrecsize
gives the size of the data to send (I think)
- I am using <winsock2.h> to connect between server and clients.
sock
is the socket of the server. - I am using <pthread.h> to manage threads. They are stored in
std::list<pthread_t*> tArray
.
The problem is : because accept()
pauses the process, and of course the loop must end to see if Crtl+C has been sent, the server can only shut down when an additional client connects.
Is there a way for interruptHandler()
to break the while
and let the program go ahead with the for
loop and next? Should I change the algorithm? On a last resort I know we can set up tags in Assembly for the program to jump to. Is there a way to do this in C++ too?
By the way, I am using <pthread.h> and <winsock2.h> because I have too (it's a student project). Thanks for helping.