首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 安全技术 > 服务器安全 >

unix 域套接字 有关问题

2013-09-06 
unix 域套接字问题25int var26varfcntl(sockfd,F_GETFL,0)27if(var&O_NONBLOCK)28{29coutO_NONBLOCK

unix 域套接字 问题

                           
 25         int var;                                              
 26         var=fcntl(sockfd,F_GETFL,0);                                   
 27         if(var&O_NONBLOCK)                                              
 28         {                                                                        
 29                 cout<<"O_NONBLOCK"<<endl;                                                 
 30         }//判断是一个阻塞的套接字
 31         while(1)                                                                           
 32         {
 33                 if((connfd=accept(sockfd,(SA*)&addr2,&len))<0)                              


 34                 {
 35                         perror("accept");                                                    
 36                         if(errno==EINTR)
 37                         {                                                                     
 38                                 cout<<errno<<endl;                                             
 39                                 continue;
 40                         }                                                                       
 41                         return -1;
 42                 }                                                                                


 43                 int pid;
 44                 pid=fork();                                                                               
 45                 if(pid==0)
 46                 {                                                                                                  
 47                         char recv1[1024];
 48                         close(sockfd);                                                                              
 49                         recv(connfd,recv1,1024,0); 
 50                         cout<<recv1<<endl;
 51                         close(connfd);
 52                 }


 53                 close(connfd);
 54         }


这是服务端的程序

struct sockaddr_un addr;
  6         addr.sun_family=AF_LOCAL;
  7         bzero(addr.sun_path,sizeof(addr));
  8         strcpy(addr.sun_path,"a.sock");
  9         int sockfd;
 10         sockfd=socket(AF_LOCAL,SOCK_STREAM,0);
 11         if(connect(sockfd,(SA*)&addr,sizeof(addr))<0)
 12         {
 13                 perror("connect");
 14                 exit(-1);
 15         }
 16         send(sockfd,"aa",2,0);
 17         close(sockfd);

出现了奇怪的现象,服务器运行后,启动客户端,服务器可以收到‘aa’,
然后紧接着,服务端就在accept出报错,bad file descriptor
服务器程序也没有crash,还一直在运行,继续启动客户端,服务器还是照常收到aa,然后报错bad file descriptor
[解决办法]
子进程在accept 之前已经CLOSE过了,也就是说这个时候你的监听SOCKET的引用计数已经为1了,所以你子进程执行accept()会报错

热点排行