Chinaunix首页 | 论坛 | 博客
  • 博客访问: 148360
  • 博文数量: 22
  • 博客积分: 428
  • 博客等级: 下士
  • 技术积分: 281
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-14 14:28
文章分类

全部博文(22)

文章存档

2013年(7)

2012年(15)

分类: BSD

2012-09-06 11:40:12

使用recvfrom来接受数据时,如果没有数据回来,会一直阻塞下去。
如果不想一直阻塞,可以通过设置socket option的方式来对 recvfrom 设置超时机制。
SO_RCVTIMEO
      Sets  the  timeout  value  that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to  complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with apartial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option  is  zero,  which  indicates  that  a receive operation shall not time out. This option takes a timeval structure. Note that not all implementa- tions allow this option to be set


点击(此处)折叠或打开

  1. struct timeval tv;
  2. int ret;
  3. tv.tv_sec = 10;
  4. tv.tv_usec = 0;
  5. if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))<0){
  6. printf("socket option  SO_RCVTIMEO not support\n");
  7. return;
  8. }
  9. if (( ret = recvfrom(s, buf, sizeof buf, 0, NULL,NULL)) < 0)
  10. {
  11.     if(ret == EWOULDBLOCK || ret== EAGAIN )
  12. printf("recvfrom timeout\n");
  13. else
  14. printf("recvfrom err:%d\n",ret);
  15. }

阅读(20193) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~