c - 发送到 : Resource temporarily unavailable (errno 11)

标签 c sockets udp sendto

我在使用 sendto 时遇到问题。

我有一个接收方,它使用 recvfrom 接收 UPD 数据包,然后使用 sendto 回复发送方。

不幸的是,我收到错误号 11(资源暂时不可用)。我正在使用两个套接字。

实际上发送了第一个数据包,但没有发送后面的数据包:

发送到::成功

错误:0。

sendto::资源暂时不可用

错误:11。

sendto::资源暂时不可用

...

这是我的代码的摘录:

    int sockfd, sockSend;

    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
            perror("socket");

    if ((sockSend = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
            perror("socket");

    if (fcntl(sockfd, F_SETOWN, getpid()) < 0) {
            perror("fcntl"); 
    }
    if (fcntl(sockfd, F_SETFL, O_RDONLY | O_NONBLOCK | FASYNC) < 0) {
            perror("fcntl"); 
    } 

    if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))
                    < 0)
            perror("bind");

在 SIGIO 处理程序中:

    len = sizeof(recv_addr);
    char buffer[payload];
    bzero(buffer, payload);
    n = recvfrom(sockfd, buffer, payload, MSG_DONTWAIT, (struct sockaddr *)&recv_addr, &len);

    while (n > 0) {

                            sprintf(response, "%d\n%d\n%d\n", items, target_buf, pb_sp);          
                            sendto(sockSend, response, strlen(response), 0, (struct sockaddr *) &recv_addr, sizeof(recv_addr));
                            // sleep(1);

                            perror("sendto :");
                            printf("error: %d.\n", errno);

     }

这个问题会不会是因为端口还很热,需要等待再使用?我试过更改端口,但没用。

更新:如果 sleep(1) 被注释掉,那么数据包实际上会被发送!

非常感谢您的帮助。

最佳答案

你得到的错误:

EAGAIN or EWOULDBLOCK: The socket is marked nonblocking and the requested operation would block. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities.

您将套接字设置为非阻塞 (O_NONBLOCK)。套接字仍在忙于发送先前的消息。在第一个完成发送之前,您不能发送另一个。这就是 sleep 有帮助的原因。

不要将其设置为非阻塞,或者在 select 说可以之后再试。

关于c - 发送到 : Resource temporarily unavailable (errno 11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5737493/

相关文章:

c - 用边长为 2^K, 2^(K - 1), ..., 4, 2, 1 的正方形填充 M x N 矩形

c++ - Winsock 程序收到 400 错误请求,您的浏览器发送了该服务器无法理解的请求

c - 套接字上带有 sendfile 的管道 C 损坏

C并发UDP套接字,奇怪的段错误

c++ - 从 recvfrom 获取未记录的错误代码

本地机器上的 python udp socket.timeout

c - 在 Eclipse 索引器中处理 Keil C51 关键字

c - 如何确定 malloc 将分配在不同的区域

c - 进程如何执行网络代码

Linux 套接字 : Zero-copy local, TCP/IP 远程