I’m currently programming a Basic Client Server messaging program in C.
The problem I have is with the Server side code.
The main part of the code is a while loop that checks for new incoming socket connections from clients.
If a client connects, a new thread is spawned that handles incoming messages. this function I use tcp_wait_for_connection( server ); is blocking.
so my question is if it’s possible to break the while loop from one of these threads without having to use Exit() so that I can close the sockets
(I’m new to Stack overflow so I did not know if I should post my complete code on here or not, I placed the most relevant part below, if you need more I’ll edit the post.
Thanks
The code goes like this:
while(1) {
client = (Socket *) malloc( sizeof(Socket) ); //allocate memory for the new client socket
if ( client == NULL ){
perror("Allocation of memory for the new client has failed");
return 1;
}
//wait for a client to connect
*client = tcp_wait_for_connection( server );
printf("Incoming client connection\n");
//get the socket descriptor for the new client socket
sd = get_socket_descriptor(client);
//insert the new client socket into the client list with the sd as ID
InsertElement(&cl, (Element)client, sd);
p_thread = (pthread_t *) malloc( sizeof(pthread_t) ); //allocate memory for the new thread handler
if ( p_thread == NULL ){
perror("Allocation of memory for the new thread has failed");
return 1;
}
//insert the new thread handler into the thread handler list
//with the sd of the corressponding client socket as ID
InsertElement(&tl, (Element)p_thread, sd);
//create the new thread
pthread_create(p_thread, NULL, HandleClient, (void*)p_thread);
}
tcp_close( *client );
tcp_close( server );
No, you can’t do that. I’d suggest that you just call the function that closes the sockets from the child threads. Use a
pthread_mutexto make sure you’re only doing it from one thread at a time. Also, inmain, handle errors intcp_wait_for_connectionthat happen because the socket was closed properly.