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

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

问题描述

假设我启动了一个线程以在端口上接收.套接字调用将在 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.

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

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