【发布时间】:2015-03-03 17:53:47
【问题描述】:
以下代码允许服务器等待客户端连接到(已经绑定的)套接字。 它在客户端连接到套接字时终止,或者在“server_run”取值为 0 时终止:这允许代码的其他部分在合适的时候关闭服务器。
static inline int wait_for_client_to_connect(int sockfd, int* server_run){
int client_found = 0;
int clientfd = 0;
struct sockaddr_in client_addr;
int addrlen=sizeof(client_addr);
if ( listen(sockfd,1) != 0 ) return -1;
while ( client_found==0 && *server_run==1 ) {
clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
if ( clientfd < 0 ) {
clientfd = 0;
if (errno==EAGAIN || errno==EWOULDBLOCK) usleep(10); // nobody connected, wait for request
else return -1; // something wrong, send error
} else { // client found, configuring socket and exit
client_found=1;
int nodelay_flag = 1;
setsockopt(clientfd, IPPROTO_TCP, TCP_NODELAY, (void*) &nodelay_flag, sizeof(int)); // disable nagle algorithm
}
}
return clientfd;
}
根据对另一个帖子(C : non blocking sockets with timeout : how to check if connection request was made?)的回答和cmets,这不是要走的路,因为它涉及忙碌的等待。
例如评论说:
“使用阻塞 IO 处理关机的标准方法是使用 信号处理程序设置关闭标志,然后在何时检查标志 听返回 -1 并将 errno 设置为 EINTR"
我很不清楚上面的代码如何适应“使用信号处理程序”......
【问题讨论】:
-
你的程序是多线程的吗?或者你提到的代码的其他部分是一个单独的程序,它与服务器共享
*server_run内存?
标签: c sockets signals server nonblocking