使用socket option-SO_RCVTIMEO为recvfrom设置超时

使用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

Sample:
  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. }

from: http://blog.chinaunix.net/uid-452173-id-3339519.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值