linxu select 返回值

本文探讨了在网络编程中使用select函数时遇到的问题,并详细解释了一个常见错误的原因及解决方法。作者通过具体代码示例展示了如何正确初始化文件描述符集以避免后续调用失败。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

曾经写过如上这样的代码,执行时怎么也得不到预想的结果!
后来,仔细看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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值