标签:
先看一代码:
fd_set readfs,writefs; int maxfd = -1; struct timeval tp; int nret = 0; unchar brcvbuf[2048]; tp.tv_sec = 2; tp.tv_usec = 0; FD_ZERO(&readfs); FD_ZERO(&writefs); FD_SET(g_isockid, &readfs); /* g_isockid 为要检测的socket*/ maxfd = Max(maxfd, g_isockid); maxfd += 1; nret = select(maxfd, &readfs, &writefs, NULL, &tp); if (FD_ISSET(g_isockid, &readfs)) /*判断是否有数据*/ { ndsize = recv(g_isockid, brcvbuf, sizeof(brcvbuf), 0); }
昨眼一看没什么大问题,但select在每个操作系统的表现不太一样,比如在HP下,就有可能没有数据但执行到recv的情况!!!
所有调用select时,必须要检测其返回值!!
上面代码修改如下:
fd_set readfs,writefs; int maxfd = -1; struct timeval tp; int nret = 0; unchar brcvbuf[2048]; tp.tv_sec = 2; tp.tv_usec = 0; FD_ZERO(&readfs); FD_ZERO(&writefs); FD_SET(g_isockid, &readfs); /* g_isockid 为要检测的socket*/ maxfd = Max(maxfd, g_isockid); maxfd += 1; nret = select(maxfd, &readfs, &writefs, NULL, &tp); if(nret < 0) { return; } if (FD_ISSET(g_isockid, &readfs)) /*判断是否有数据*/ { ndsize = recv(g_isockid, brcvbuf, sizeof(brcvbuf), 0); }
标签:
原文地址:http://www.cnblogs.com/xiaole10368/p/5384368.html