DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define BUFFER 800
#define SERV_PORT 3333
int main()
{
int sockfd,n;
socklen_t len;
socklen_t src_len;
struct sockaddr_in servaddr, cliaddr;
char msg[BUFFER];
struct timeval tm;
fd_set rd_fd, wr_fd, ex_fd;
sockfd = socket(AF_INET, SOCK_DGRAM, 0); /* create a socket */
/* init servaddr */
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
/* bind address and port to socket */
if(bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1)
{
perror("bind error");
exit(1);
}
src_len = sizeof(cliaddr);
FD_ZERO(&rd_fd);
FD_SET(sockfd, &rd_fd);
tm.tv_sec = 0;
tm.tv_usec = 0;
while(1)
{
FD_ZERO(&rd_fd);
FD_SET(sockfd, &rd_fd);
tm.tv_sec = 1;
tm.tv_usec = 0;
if(select(sockfd + 1, &rd_fd, NULL, NULL, &tm) <= 0){
continue;
}
else
{
printf("%d, %d/n", tm.tv_sec, tm.tv_usec);
printf("there is data/n");
if(recvfrom(sockfd, msg, BUFFER, 0, (struct sockaddr *)&cliaddr, &src_len)< 0)
{
perror("receive error!/n");
exit(0);
}
printf("%s/n", msg);
sleep(5);
}
}
return 0;
}

 

曾经写过如上这样的代码,执行时怎么也得不到预想的结果!
后来,仔细看man select
On success, select() and pselect() return the number of file descriptors contained in the three returned descriptor sets(that  is,  the  total  number  of  bits  that are set in readfds, writefds, exceptfds) which may be zero if the timeout expires before anything interesting happens.  On error, -1 is returned, and errno is set appropriately;  the  sets  and timeout become undefined, so do not rely on their contents after an error. 
原来第一次select的时候出错了,导致rd_fd和tm(主要是rd_fd)的值 become undefined,进而导致以后的select调用的失败!
解决办法:
在1处(while循环内的开头),添加如下代码:
FD_ZERO(&rd_fd);
FD_SET(sockfd, &rd_fd);
tm.tv_sec = 1;
tm.tv_usec = 0;

posted on   DoubleLi  阅读(496)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示