CmdChannel昨天移植到Ubuntu上,功能都OK,就是发现CPU有点不对,怎么一直在90%的使用率呢?但为什么在Windows下运行是正常的呢?
struct timeval val;
fd_set rd;
int maxfd = -1;
int ret = 1;
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
val.tv_sec = 0;
val.tv_usec = 1000;
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
cc_Global.telnet.run = 1;
while(cc_Global.telnet.run)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
maxfd = cc_TelnetServer_SetFd(&rd);
![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
ret = select(maxfd + 1, &rd, NULL, NULL, &val);
![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
if(ret > 0)
![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
![](http://www.cppblog.com/Images/dot.gif)
想来是select的问题,因为select本来就是放置100%CPU的。对着帮助文档,先检查maxfd,没错啊,再检查rd,然后是timeval,也没有错啊~是timeval设定的太短?换成val.sec = 5,问题依旧~
折腾很久,突然发现,while循环在第一次运行时是有间隔的,但其后就开始100%了。突然想起,使用select的一个注意事项就是fdset每次要重新设置,因为select函数会修改其值。那么timeval也是如此吗?于是修改代码:
struct timeval val;
fd_set rd;
int maxfd = -1;
int ret = 1;
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
cc_Global.telnet.run = 1;
while(cc_Global.telnet.run)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
maxfd = cc_TelnetServer_SetFd(&rd);
![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
val.tv_sec = 0;
val.tv_usec = 1000;
![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
ret = select(maxfd + 1, &rd, NULL, NULL, &val);
![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
if(ret > 0)
![](http://www.cppblog.com/Images/dot.gif)
果然如此,timeval被select函数清零了~
查看select函数的原型:
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
其timeout确实不是一个const量。。。
windows和unix下的函数间的微小差异害死人啊~