本版版主招募中

 
标题: 使用select()函数的服务端奇怪问题
cinuxer
LU新生
Rank: 1



UID 93566
精华 0
积分 1
帖子 1
活跃指数 1
LU金币 2 个
LU金条 0 个
阅读权限 10
注册 2007-7-29
 
发表于 2007-7-29 21:07  资料  个人空间  短消息  加为好友 
使用select()函数的服务端奇怪问题

代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <time.h>
#include <sys/times.h>
#include <sys/select.h>

void init_addr(struct sockaddr_in *addr);

int main()
{
int sockfd, clilen, listenfd, connfd;
int n, i, maxfd, maxi, nready, client[FD_SETSIZE];
fd_set rset, allset;
struct sockaddr_in addr, cliaddr;
char str[20];
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
  fprintf(stderr, "socket error");
  exit(-1);
}

init_addr(&addr);
if(bind(listenfd, (struct sockaddr *)&addr, sizeof(addr)) < 0){
  fprintf(stderr, "bind error");
  exit(-1);  
}
listen(listenfd, 100);
FD_ZERO(&allset);
FD_SET(listenfd, &allset);
maxfd = listenfd;
for(i = 0; i < FD_SETSIZE; i++)
  client = -1;
maxi = -1;
while(1){
  rset = allset;
  nready = select(maxfd + 1, &rset, NULL, NULL, NULL);
  fprintf(stderr, "%d", nready);
  fprintf(stderr, "%d", FD_ISSET(listenfd, &rset));
  if(FD_ISSET(listenfd, &rset)) {
   clilen = sizeof(cliaddr);
   connfd = accept(listenfd, (struct sockaddr *)&cliaddr,
    &clilen);
      for(i = 0; i < FD_SETSIZE; i++)
    if(client < 0) {
     client = connfd;
     break;}
   FD_SET(connfd, &allset);
   if(connfd > maxfd)
    maxfd = connfd;
   if(i > maxi)
    maxi = i;
   if(--nready <= 0)
    continue;
  }
  
  for(i = 0; i < maxi; i++) {
   if((sockfd = client ) < 0)
    continue;
   if(FD_ISSET(sockfd, &rset)) {
   if(n = recv(sockfd,str,sizeof(str), 0) == 0)
    {
     close(sockfd);
     FD_CLR(sockfd, &allset);
     client = -1;
    }
    else {
    send(sockfd, "def", sizeof("def"), 0);
    }
    if(--nready <= 0)
     break;
   }
  }
}
}
在程序中我加入了fprintf(stderr, "%d", nready);fprintf(stderr, "%d", FD_ISSET(listenfd, &rset));来验证,nready的值是1,表明有一个连接,但是FD_ISSET(listenfd, &rset)的值却是0,导致程序进入死循环,整个屏幕显示的都是10101010**********,FD_ISSET(listenfd, &rset)的值怎么会是0???

顶部
 



当前时区 GMT+8, 现在时间是 2008-10-7 20:18
乐悠LoveUnix论坛-京ICP备05005823号

Thanks to Discuz!  © 2001-2007    Power by LoveUnix.net
Processed in 0.113380 second(s), 6 queries , Gzip enabled

清除 Cookies - 联系我们 - 乐悠LoveUnix - Archiver