Linux UDP套接字:没有通知select()?

时间:2016-06-27 21:56:39

标签: linux sockets udp

我有这样的Linux UDP套接字代码:

//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客户端发送的内容。

但是,如果我在recvfrom之后添加select(),请参阅下面的代码,当我从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 );
    }
}

1 个答案:

答案 0 :(得分: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 );
}
}