2016-06-27 75 views
1

我的Linux UDP插座這樣的代碼:Linux UDP套接字:select()沒有通知?

//create the UDP socket and bind to a local port 5001 
//sockfd = socket(AF_INET, UDP, 0); 
//bind(sockfd, .., ...); 
recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr *)&remote_addr, &addrlen); 
printf("%s\n", buffer); 

在這裏,recvfrom工作正常,並且printf上面可以打印我從ncat客戶端發送。

但如果我select()後把recvfrom,見下面的代碼,select()不會返回,當我從ncat客戶端發送數據到這個插座。

max_fd = 0 
FD_ZERO(&read_set); 
FD_SET(sockfd, &read_set); 

while (1) { 
    i = select(max_fd + 1, &read_set, NULL, NULL, NULL); //==> !!! select() is not returned from ncat sent data to this socket 
    if (i < 0 && errno != EINTR) { 
     ............. 
    } 
    for (current_fd = 0; current_fd <= max_fd; current_fd++){ 
     if (!FD_ISSET(current_fd, &read_set)) 
       continue; 
     nbytes = recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr *)&remote_addr, &addrlen); 
     printf("%d bytes received \n", nbytes); 
    } 
} 
+0

這是'C'或'C++',我想'C'但我寧願不承擔。 –

+1

您需要每次在循環中恢復read_ste。 – EJP

回答

0
while (1) { 
FD_ZERO(&read_set); 
FD_SET(sockfd, &read_set); 
i = select(max_fd + 1, &read_set, NULL, NULL, NULL); 
if (i < 0 && errno != EINTR) { 
    ............. 
} 
for (current_fd = 0; current_fd <= max_fd; current_fd++){ 
    if (!FD_ISSET(current_fd, &read_set)) 
      continue; 
    nbytes = recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr *)&remote_addr, &addrlen); 
    printf("%d bytes received \n", nbytes); 
} 
}