套接字关闭时取消阻止接收 [英] Unblock recvfrom when socket is closed

查看:122
本文介绍了套接字关闭时取消阻止接收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我启动了一个线程以在端口上进行接收.套接字调用将在recvfrom上阻止. 然后,以某种方式在另一个线程中,关闭套接字.

Let's say I start a thread to receive on a port. The socket call will block on recvfrom. Then, somehow in another thread, I close the socket.

在Windows上,这将取消阻止recvfrom,并且我的线程执行将终止.

On Windows, this will unblock recvfrom and my thread execution will terminate.

在Linux上,这不会取消阻止recvfrom,因此,我的线程永远坐着不动,并且线程执行不会终止.

On Linux, this does not unblock recvfrom, and as a result, my thread is sitting doing nothing forever, and the thread execution does not terminate.

有人可以帮助我了解Linux上发生的情况吗?当套接字关闭时,我希望recvfrom取消阻止

Can anyone help me with what's happening on Linux? When the socket is closed, I want recvfrom to unblock

我一直在阅读有关使用select()的知识,但我不知道如何在特定情况下使用它.

I keep reading about using select(), but I don't know how to use it for my specific case.

推荐答案

在套接字上调用shutdown(sock, SHUT_RDWR),然后等待线程退出. (即pthread_join).

Call shutdown(sock, SHUT_RDWR) on the socket, then wait for the thread to exit. (i.e. pthread_join).

您会认为close()会解除对recvfrom()的阻止,但在Linux上不会.

You would think that close() would unblock the recvfrom(), but it doesn't on linux.

这篇关于套接字关闭时取消阻止接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆