日期:2014-05-16  浏览次数:20649 次

请教高手,linux中select函数的问题
最近刚刚学习linux下的socket编程,在实现多客户端通信的时候,服务器端原本用gethostbyname函数可以成功,但是现在想用getAddrinfo函数使得IPv4、IPv6都能用时,select函数无法判断客户端的连接,程序被阻塞在select这一句,不知道哪里出问题了,请教各位高手帮忙解答下,谢拉啊!

Server端程序
#include<sys/socket.h>
#include<iostream>
#include<sys/types.h>
#include<strings.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/select.h>
#include<pthread.h>
#define MAXSIZE 1024
#define MAXSOCKET 3
int count=0;
int get_file;
fd_set readfds;
void *get_client(void *);
using namespace std;

int main(int argc,char *argv[])
{
  if(argc<3)
  {
  cout<<"Please enter port or file path:"<<endl;
  exit(1);
  }
  int serverSock,confd;
  //char *server_file;
  struct sockaddr_in addr;
  pthread_t thread_test;
  socklen_t addr_len=sizeof(addr);
  if((serverSock=socket(AF_INET,SOCK_STREAM,0))<0)
  {
  cout<<"socket failed!"<<endl;
  exit(1);
  }
  in_port_t port=atoi(argv[1]);
  if((get_file=open("/home/tracy/software/sock_file/test",O_WRONLY|O_CREAT|O_APPEND,S_IRUSR|S_IWUSR))==-1)
  {
  cout<<"Can't find file!"<<endl;
  exit(1);
  }
  // server_file=get_file;
  bzero(&addr,sizeof(addr));
  addr.sin_family=AF_INET;
  addr.sin_port=htons(port);
  // addr.sin_port=htons("4000");
  addr.sin_addr.s_addr=htonl(INADDR_ANY);
  if(bind(serverSock,(struct sockaddr*) &addr,sizeof(addr))<0)
  {
  cout<<"bind failed!"<<endl;
  exit(1);
  }
  if(listen(serverSock,3)<0)
  {
  cout<<"listen failed!"<<endl;
  exit(1);
  }
  while(1)
  {
  FD_ZERO(&readfds);
  FD_SET(serverSock,&readfds);
  if(select(MAXSOCKET+1,&readfds,NULL,NULL,0))
  {
  if(FD_ISSET(serverSock,&readfds)>0)

  {
  confd=accept(serverSock,(struct sockaddr*)&addr,&addr_len);
  count=count+1;
  pthread_create(&thread_test,NULL,&get_client,(void*)confd);
  }
  }

  }

 }
  void *get_client(void *newSock)
{
  char buffer[MAXSIZE];
  int recv_write;
  // char *server_file;
  /*if(count<=MAXSOCKET)
  {
  if(recv((int)newSock,buffer,MAXSIZE,0)<0)
  {
  cout<<"receive failed!"<<endl;
  return NULL;
  }
  cout<<"connect client:"<<endl;
  cout<<buffer<<endl;
  if(send((int)newSock,"hello,I'm server!",strlen("hello,I'm server!")+1,0)<0)
  {
  cout<<"send failed!"<<endl;
  return NULL;
  }
  close((int)newSock);
  }
  else
  send((int)newSock,"client full!",strlen("client full!&qu