views:

193

answers:

2

I'm just starting to learn how network programming in C works, and I've written a small program that sends messages to and from a UNIX terminal. I'm using pthreads in my program, one of which essentially just waits on recvfrom() to receive a message.

However, I want to be able to close all threads properly if the users chooses to quit the program. The way I have it set up right now, a different thread just cancels the thread waiting on recvfrom, but I'm worried this might not be a good idea since I'm leaving sockets unclosed and I'm not freeing all the memory I allocated.

Is there a way to cancel a recvfrom() call, or some way to run a certain routine upon cancelling a pthread?

Thanks.

+1  A: 

If you use pthread_kill to send a signal to the thread, recvfrom() should return -1 with errno set to EINTR - you can then check for the "application is now exiting" condition and finish up gracefully.

caf
+1  A: 

Another approach would be to maintain a list of open connection matched with thread id's. Then whenever you cancel a thread go through the list to find it's socket and call close on the socket.

Robert S. Barnes