gpt4 book ai didi

当同一个套接字上的发送/接收正在进行时,套接字是否可以从另一个线程关闭?

转载 作者:太空狗 更新时间:2023-10-29 16:38:41 25 4
gpt4 key购买 nike

当同一套接字上的发送/接收正在进行时,是否可以从另一个线程关闭套接字?

假设一个线程正在阻塞 recv 调用,而另一个线程关闭了同一个套接字,recv 调用中的线程会知道这一点并安全退出吗?

我想知道不同操作系统/平台之间的行为是否会有所不同。如果是,它在 Solaris 中的表现如何?

最佳答案

在 linux 中关闭套接字不会唤醒 recv()。此外,作为 @jxh说:

If a thread is blocked on recv() or send() when the socket is closed by a different thread, the blocked thread will receive an error. However, it is difficult to detect the correct remedial action after receiving the error. This is because the file descriptor number associated with the socket may have been picked up by yet a different thread, and the blocked thread has now been woken up on an error for a "valid" socket. In such a case, the woken up thread should not call close() itself.

The woken up thread will need some way to differentiate whether the error was generated by the connection (e.g. a network error) that requires it to call close(), or if the error was generated by a different thread having called close() on it, in which case it should just error out without doing anything further to the socket.

因此,避免这两个问题的最佳方法是调用 shutdown() 而不是 close()shutdown() 将使文件描述符仍然可用,因此不会被另一个描述符分配,也将唤醒 recv() 错误和线程recv() 调用可以正常方式关闭套接字,就像发生正常错误一样。

关于当同一个套接字上的发送/接收正在进行时,套接字是否可以从另一个线程关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3589723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com