- 论坛徽章:
- 0
|
本帖最后由 liqingfang 于 2011-06-08 11:50 编辑
现在linux平台用select还是存在的,这个只是测试代码,但应该没问题,出错的原因老是select调用返回-1,errno的信息是Bad address,但select之前的bind是没有报错的,怎么会是Bad address呢,望各位高手指点。谢谢!- struct sockaddr_in myname,cliaddr;
- fd_set fdread;
- struct timeval timeout;
- pid_t pid;
- socklen_t addrlen;
- int new_sock = 0;
- myname.sin_family = AF_INET;
- myname.sin_port = htons(7878);
- bzero(&myname.sin_zero,8);
- inet_aton("192.168.1.216",&myname.sin_addr);
-
-
- int sock = socket(AF_INET,SOCK_STREAM,0);
- if(sock<0)
- {
- syslog(LOG_ERR,"can not create socket");
- return -1;
- }
- fcntl(sock,F_SETFL,O_NONBLOCK);
- int flag = 0;
- if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&flag,sizeof(flag))<0)
- {
- syslog(LOG_ERR,"can not set sock opt");
- return -1;
- }
-
- syslog(LOG_INFO,"before bind errno is %s",strerror(errno));
- if(bind(sock,(struct sockaddr *)&myname,sizeof(myname))<0)
- {
- syslog(LOG_ERR,"can not bind addr");
- return -1;
- }
- syslog(LOG_INFO,"after bind errno is %s",strerror(errno));
- if(listen(sock,7)<0)
- {
- syslog(LOG_ERR,"can not listen");
- return -1;
- }
- syslog(LOG_INFO,"after listen errno is %s",strerror(errno));
- //fd_set fdread;
- syslog(LOG_INFO,"Listening for connections on port %d\n",htons(myname.sin_port));
-
- while(1)
- {
- while(1)
- {
-
- FD_ZERO(&fdread);
- FD_SET(sock,&fdread);
-
- timeout.tv_sec = 0;
- timeout.tv_usec = 500000;
-
- syslog(LOG_INFO,"before select errno is %s",strerror(errno));
- if(!FD_ISSET(sock,&fdread))
- {
- syslog(LOG_INFO,"fd is not set");
- }
- int reval = select(sock+1,&fread,NULL,NULL,&timeout);
- //syslog(LOG_INFO,"select get val is %d\n",reval);
- // printf("errno is %d\n",errno);
- // perror("perror");
- // printf("sterror:%s\n",strerror(errno));
- if(reval<0)
- {
- syslog(LOG_INFO,"Error");
- syslog(LOG_INFO,"errno is %s",strerror(errno));
- }
- else if(reval==0)
- {
- syslog(LOG_INFO,"Wait----");
- continue;
- }
- else
- {
- syslog(LOG_INFO,"(((((()))))))");
-
- new_sock = accept(sock,0,0);
-
- ------
- }
- }
复制代码 log输出为:
|
|