【发布时间】:2011-01-14 06:01:54
【问题描述】:
我正在使用 select() 来确定非阻塞连接何时连接、正在连接或无法连接;在 Linux 上使用 TCP 套接字。我的实际 TCP 连接连接并正常工作,这只是为了检测它们的状态。
奇怪的是,我的代码总是首先给我我认为的 CONNECTIONFAILED .. 在 cout(任何 cout)之后,下一次调用 select() 给了我我认为的 已连接。套接字是否连接无关紧要。
我已经验证我使用了一个好看的套接字(在这种情况下它的 int id 是 3,就像我说的那样,它确实可以通过连接到侦听 netcat 来验证实际连接)
我的顶级代码是
while(1)
{
state = networking.connectionStatus(socketId);
.. [cout would go here or not, as described above]
if(state == CONNECTED) { // connected! }
else .. // connecting, or connection failed code
}
我的选择代码,在这个传递给 connectionStatus 的非阻塞套接字上运行
myStateType connectionStatus(int socket)
{
struct timeval tv;
tv.tv_sec = 0; tv.tv_usec = 0; // no timeout, immediately return from select()
fd_set ourFdSet;
FD_ZERO(&ourFdSet); // zero the set
FD_SET(socket, &ourFdSet); // put our socket in to this set
// Switch to figure out if we can write to our fd yet
switch(select(socket + 1, NULL, &ourFdSet, NULL, &tv))
{
case -1: // connection failed, actual error from select()
return CONNECTIONFAILED;
break;
case 0: // no fds ready to write, still connecting?? can someone verify this is true
return CONNECTING;
break;
case 1: // now we have 1 fd ready to write, but look closer..
// Examine our socket at the socket level for errors.. if < 0 then getsockopt fail
if(getsockopt(socket, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
return CONNECTIONFAILED;
if(error == 0) return CONNECTED;
if(error == EINPROGRESS) return CONNECTING;
// otherwise, failure.. (a real error)
return CONNECTIONFAILED;
.. end of function ..
那么,这里的 cout 会发生什么?这一切都在正确的轨道上吗?所有手册页和互联网资源似乎都同意..
【问题讨论】:
-
您应该调用 FD_ISSET() 来确定您的套接字是否已准备好写入。单独使用 select() 的返回值可能是不够的。
-
我确实试过了,但后来把它拿出来了——没有目的,集合里只有一个 fd。