<p></p><div class="codetitle"><span><a class="copybut" data="20496" id="copybut20496"><u>复制代码</u></a></span> 代码如下:</div><div class="codebody" id="code20496"><br>#include <stdio.h><br>#include <string.h><br>#include <unistd.h><br>#include <errno.h><br>#include <unistd.h><br>#include <stdlib.h><br>#include <sysexits.h><br>#include <time.h><br>#include <sys/time.h><br>#include <sys/types.h><br>#include <sys/uio.h><br>#include <sys/ioctl.h><br>#include <sys/types.h><br>#include <sys/socket.h><br>#include <net/if.h><br>#include <netinet/in.h><br>#include <arpa/inet.h>
<p>#ifdef __ENABLED_DEBUG_INFO_OUTPUT__<br> #define DEBUG_OUTPUT(format) printf( "\nFile: %s : Line: %d ->Function: %s\n"format"\n", __BASE_FILE__, __LINE__, __FUNCTION__ )<br> #define DEBUG_OUTPUT_PARA(format,...) printf( "\nFile: %s : Line: %d ->Function: %s\n"format"\n", __BASE_FILE__, __LINE__, __FUNCTION__, __VA_ARGS__ )<br>#else<br> #define DEBUG_OUTPUT(format)<br> #define DEBUG_OUTPUT_PARA(format,...)<br>#endif</p>
<p>// @brief 非阻塞等待套接字是否可读/写<br>// @param[in] sockfd 套接字描述符<br>// @param[in] bWhichSet true - 可读集; false - 可写集;<br>// @param[in] uiTimeOutMS 超时时长(单位:微秒);<br>// @pre scokfd 有效套接字描述符,即大于等于零(>=0)<br>// @return 此函数执行结果<br>// @return 0 - 可以读/写;<br>// -1 - 参数不合法;<br>// -2 - 检测已超时;<br>// @note uiTimeOutMS 超时时长,设为零(0),则不等待超时<br>static inline int<br>wait_rw_able( int sockfd,<br> bool bWhichSet,<br> unsigned int uiTimeOutMS )<br>{<br> // 默认为检测已超时<br> int iReturnValue = -2;</p>
<p> // 可读描述符集<br> fd_set rset;<br> // 可写描述符集<br> fd_set wset;</p>
<p> // select 将等待的时间<br> timeval tv;</p>
<p> do // 非循环,只是为了保证函数只有一个返回点<br> {<br> // 参数不合法<br> if ( 0 > sockfd )<br> {<br> iReturnValue = -1;<br> break;<br> }</p>
<p> // 注:每次调用 select 之前都要重设一次!<br> tv.tv_sec = 0;<br> tv.tv_usec = uiTimeOutMS;</p>
<p> // 检测是否可读<br> if ( true == bWhichSet )<br> {<br> // 清除其所有位<br> FD_ZERO( &rset );<br> // 设置关心的描述符<br> FD_SET( sockfd, &rset );</p>
<p> // 大于零(0) - 有套接字可读,零(0) - 没有,负数 - 出错<br> if ( 0 < select( sockfd + 1, // 从描述符零(0)开始搜索,故此要对套接字描述符加壹(1)<br> &rset, // 可读描述符集<br> NULL, // 可写描述符集<br> NULL, // 异常描述符集<br> &tv ) ) // 等待时间<br> {<br> // 可读描述符是我们的套接字<br> if ( FD_ISSET( sockfd, &rset ) )<br>   |
|