linux - select() 似乎与 cout/stdout 相关?

标签 linux sockets select

我正在使用 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 在这里播放是怎么回事?这一切都在正确的轨道上吗?所有手册页和互联网资源似乎都同意......

最佳答案

select() 返回 -1 并不表示连接失败 - 它表示 select() 本身遇到了错误。您应该返回一些不同的东西(或者至少,在该路径中放置一个 perror("select") )。这同样适用于 getsockopt() 失败。添加这些将有助于调试问题。

其余部分看起来不错 - 如果套接字不可写(select() 返回零),则连接尝试仍在进行中。尽管您做出相反的保证,但看起来您确实可能混淆了文件描述符。

关于linux - select() 似乎与 cout/stdout 相关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4688379/

相关文章:

linux - 如何删除字符设备中的数据

java - 应用程序的客户端-服务器架构

java - 从 java 套接字发送时在整数数组中添加空白字符串

mySQL 给出的结果比我的查询预期的要多

postgresql - 在 Postgres 中创建函数时出错

linux - 无法在用户定义的网络上发现 docker 容器

linux - 当我的 linux 系统重新启动时,我应该使用什么 lilo 选项来设置要运行的脚本?

c# - 客户端上的 10048 套接字错误?可能的原因?

MySQL只计算新记录

linux - 如何使用 ssh 和 Travis CI 进行自定义部署?