LoveUnix » 编程开发 & Rational » 使用select()函数的服务端奇怪问题
让LU留住您的每

一天 让LU博客留住您的每一天
2007-7-29 21:07 cinuxer
使用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 [i] = -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 [i] < 0) {
     client [i]= 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 [i]) < 0)
    continue;
   if(FD_ISSET(sockfd, &rset)) {
   if(n = recv(sockfd,str,sizeof(str), 0) == 0)
    {
     close(sockfd);
     FD_CLR(sockfd, &allset);
     client [i] = -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???

页: [1]


Powered by Discuz! Archiver 5.5.0  © 2001-2006 Comsenz Inc.