我正在使用 c 套接字来实现可靠的 UDP 协议(protocol)。我正在使用以下代码在我正在等待确认的套接字上设置超时。我不确定为什么会收到错误号 11,资源暂时不可用。
//set timer for recv_socket
struct timeval tv;
tv.tv_usec = TIMEOUT_MS;
if(setsockopt(rcv_sock, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0){
printf("Error setting the socket timeout.\n");
}
int recv_msg_len;
if(recv_msg_len = recvfrom(rcv_sock, ackBuffer,sizeof(ackBuffer), 0,
(struct sockaddr *) &servAddr2, &fromSize) < 0){
//timeout reached
printf("Error Reporting: %d : %s\n", errno, strerror(errno));
num_timeouts++;
}
我也尝试过评论中提到的select方法。我在一个循环中有以下代码,但 recvfrom 永远不会超时。
fd_set set;
FD_ZERO(&set); /* empties the set */
FD_CLR(rcv_sock,&set); /* removes FD from the set */
FD_SET(rcv_sock,&set); /* adds FD to the set */
if(select(rcv_sock + 1, &set, NULL, NULL, &tv) < 0){
printf("\nError Reporting: %d : %s\n\n", errno, strerror(errno));
return -1;
}
if(!FD_ISSET(rcv_sock,&set)){ /* true if FD is in the set */
printf("socket is not set properly.\n");
}
最佳答案
当在阻塞套接字上调用 recvfrom()
并且使用 setsockopt()
设置了超时时,出现错误 EAGAIN (11 )
以防调用 recvfrom()
超时(即:在指定为超时的时间段内未收到任何数据)。
来自 man recvfrom
的逐字记录:
RETURN VALUE
...
ERRORS
... .
EAGAIN or EWOULDBLOCK The socket is marked non-blocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received. ...
要解决这个问题:只需再次调用 recvfrom ()
... ;-)
关于c - Errno : 11, 资源暂时不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554691/