开发者

Cancel UDP recvfrom in C on Unix

开发者 https://www.devze.com 2022-12-22 20:57 出处:网络
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 essen

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 memor开发者_如何学运维y I allocated.

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

Thanks.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号