对于阻塞 UDP 套接字,select() 返回(无错误)且 FD_ISSET(socket) 为 true,但后续的 recvmsg() 会阻塞

发布于 2025-01-18 17:38:34 字数 976 浏览 0 评论 0原文

创建了一个服务端UDP套接字,没有o_nonblock flag,然后在一段时间内,select() call returns(无错误)和socket FD是从fd_isset测试的。但是,随后,当我使用recvmsg()从套接字阅读时,呼叫块。

简化的代码如下:

int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in sock;
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = <some IP>;
sock.sin_port = htons(<some port number>);
int rc = bind(fd, (struct sockaddr *)&sock, sizeof(sock));
// no error

while (1) {
   fd_set rset; // read
   FD_ZERO(&rset);
   FD_SET(fd, rset);
   rc = select(fd + 1, &rset, NULL, NULL, NULL); // no timeout
   if (rc <= 0) {
       // handles error or zero fd
       continue;
   }

   if (FD_ISSET(fd, rset)) {
       struct msghdr msg;
       // set up msg ...
       ret = recvmsg(fd, &msg, 0); // <------- blocks here
       // check ret
   }
}

UDP插座可以读取但阅读会阻塞哪些条件?

A service-side UDP socket was created without the O_NONBLOCK flag, then in a while loop, the select() call returns (no error) and the socket fd is tested true from FD_ISSET. However, subsequently when I read from the socket using recvmsg(), the call blocks.

The simplified code is as follows:

int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in sock;
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = <some IP>;
sock.sin_port = htons(<some port number>);
int rc = bind(fd, (struct sockaddr *)&sock, sizeof(sock));
// no error

while (1) {
   fd_set rset; // read
   FD_ZERO(&rset);
   FD_SET(fd, rset);
   rc = select(fd + 1, &rset, NULL, NULL, NULL); // no timeout
   if (rc <= 0) {
       // handles error or zero fd
       continue;
   }

   if (FD_ISSET(fd, rset)) {
       struct msghdr msg;
       // set up msg ...
       ret = recvmsg(fd, &msg, 0); // <------- blocks here
       // check ret
   }
}

What are some of the conditions that the UDP socket is readable but reading it would block?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文