在 Win32 中,有没有办法测试套接字是否是非阻塞的?
在 Win32 中,有没有办法测试套接字是否是非阻塞的?
In Win32, is there a way to test if a socket is non-blocking?
在 POSIX 系统下,我会执行以下操作:
Under POSIX systems, I'd do something like the following:
int is_non_blocking(int sock_fd) {
flags = fcntl(sock_fd, F_GETFL, 0);
return flags & O_NONBLOCK;
}
然而,Windows 套接字不支持 fcntl().非阻塞模式是使用带有 FIONBIO 的 ioctl 来设置的,但似乎没有办法使用 ioctl 来获取当前的非阻塞模式.
However, Windows sockets don't support fcntl(). The non-blocking mode is set using ioctl with FIONBIO, but there doesn't appear to be a way to get the current non-blocking mode using ioctl.
Windows 上是否还有其他调用可用于确定套接字当前是否处于非阻塞模式?
Is there some other call on Windows that I can use to determine if the socket is currently in non-blocking mode?
一个稍微长一点的答案是:不,但你通常会知道它是否是,因为它相对明确.
A slightly longer answer would be: No, but you will usually know whether or not it is, because it is relatively well-defined.
除非您使用 FIONBIO
明确ioctlsocket()
或将它们交给 WSAAsyncSelect
或 WSAEventSelect代码>.后两个函数秘密地"将套接字更改为非阻塞.
All sockets are blocking unless you explicitly ioctlsocket()
them with FIONBIO
or hand them to either WSAAsyncSelect
or WSAEventSelect
. The latter two functions "secretly" change the socket to non-blocking.
由于您知道是否调用了这三个函数之一,因此即使您无法查询状态,它仍然是已知的.明显的例外是,如果该套接字来自某个 3rd 方库,而您不知道它究竟对套接字做了什么.
Since you know whether you have called one of those 3 functions, even though you cannot query the status, it is still known. The obvious exception is if that socket comes from some 3rd party library of which you don't know what exactly it has been doing to the socket.
旁注:有趣的是,套接字可以同时阻塞和重叠,这看起来并不直观,但它有点道理,因为它们来自相反的范式(准备与完成).
Sidenote: Funnily, a socket can be blocking and overlapped at the same time, which does not immediately seem intuitive, but it kind of makes sense because they come from opposite paradigms (readiness vs completion).