我正在练习POSIX编程套接字,我的服务器存在以下问题,当我终止其中一个客户端时,函数pselect获取错误文件描述错误(我认为它的错误= EBADF),你能帮我写一下怎么能我在代码中避免使用它?
这是我写的:
void doServer(int fd) {
//fd is the listening socket (there is only one)
int maxfd = fd;
//base, and reading fd set
fd_set base_rfds, rfds;
int i;
sigset_t mask, oldmask;
//zero out base fd set
FD_ZERO(&base_rfds);
//add listening socket to base fd set
FD_SET(fd, &base_rfds);
//add SIGINT to blocking signal mask
sigemptyset (&mask);
sigaddset (&mask, SIGINT);
sigprocmask (SIG_BLOCK, &mask, &oldmask);
//main server loop (block on pselect untill fd changes or we get signal)
while(!stop){
rfds=base_rfds;
//call pselect with oldmask to not block SIG_INT
if(pselect(maxfd+1,&rfds,NULL,NULL,NULL,&oldmask)>0){
if(FD_ISSET(fd,&rfds)){
//connect client
maxfd+=add_new_client(fd, &base_rfds);
//remove listening socket from reading fd set
FD_CLR(fd,&rfds);
}
//remove listening socket from base fd set
FD_CLR(fd,&base_rfds);
handle_connection(rfds,&base_rfds,maxfd);
//add listening socket back into base fd set
FD_SET(fd,&base_rfds);
}
else{
if(EINTR==errno) continue;
ERR("select");
}
}
//close all of fd's from connected clients
for(i=0;i<maxfd;i++)
if(FD_ISSET(i,&base_rfds) && TEMP_FAILURE_RETRY(close(i))<0)ERR("close");
sigprocmask (SIG_UNBLOCK, &mask, NULL);
}
修改 这是add_new_client函数:
int add_new_client(int sfd, fd_set *base_rfds){
int nfd,new_flags;
//accept now if we can (non-blocking)
if((nfd=TEMP_FAILURE_RETRY(accept(sfd,NULL,NULL)))<0) {
if(EAGAIN==errno||EWOULDBLOCK==errno) return 0;
ERR("accept");
}
//remember to make the fd non-blocking
//get current flags, add O_NONBLOCK
new_flags = fcntl(nfd, F_GETFL) | O_NONBLOCK;
//apply new flags
fcntl(nfd, F_SETFL, new_flags);
//add discriptor to base fd set
FD_SET(nfd,base_rfds);
return 1;
}
答案 0 :(得分:1)
您正在选择已关闭的套接字。关闭套接字时,需要将其从FD集中删除。你对这套装置的处理似乎很乐观。例如,您无法确定添加新客户端是否真的会增加最大FD。我也不明白为什么你要从集合中移除一次监听套接字,更不用说两次,然后重新恢复它。您需要查看In [91]: timeit current_flows+current_flows
1000 loops, best of 3: 413 µs per loop
In [92]: timeit C_csc+C_csc
1000 loops, best of 3: 223 µs per loop
的一些示例代码。这一切都很奇怪。