一个poll函数使用的例子:(代码抄自《UNIX网络编程》P147),for循环嵌套很深,例子很一般。此处仅做记录代码使用。
int main(int argc, char **argv)
{
INT iConfd = 0;
INT iReadLen = 0;
INT iMaxFd = 0;
INT iMaxIndex = 0;
struct pollfd astPollfd[BUF_LEN_16];
INT iIndex = 0;
INT iReady = 0;
CHAR szBuf[BUF_LEN_256] = {0,};
/* 注册信号 */
(VOID)reg_sigal(abnomalExit);
/* 初始化 */
process_init();
/* 创建服务器 */
if(ERROR_SUCCESS != sock_CreateServer(SERVER_PORT, &g_iListenSocket))
{
printf("create server failed.\n");
return -1;
}
astPollfd[0].fd = g_iListenSocket;
astPollfd[0].events = POLLRDNORM;
for(iIndex = 1; iIndex<BUF_LEN_16; iIndex++)
{
astPollfd[iIndex].fd = -1;
}
for(;;)
{
iReady = poll(astPollfd, iMaxIndex + 1, -1);
if(0 != (astPollfd[0].revents & POLLRDNORM))
{
iConfd = accept(g_iListenSocket, NULL, NULL);
for(iIndex = 1;iIndex < BUF_LEN_16;++iIndex)
{
if(astPollfd[iIndex].fd<0)
{
astPollfd[iIndex].fd = iConfd;
break; /* 跳出内层循环 */
}
}
if (iIndex == BUF_LEN_16)
{
printf("too many client.\n");
break; /* 跳出外层循环 */
}
/* 将链接socket加入监听 */
astPollfd[iIndex].events = POLLRDNORM;
if(iIndex>iMaxIndex)
{
iMaxIndex = iIndex;
}
if(--iReady < 0)
{
continue;
}
}
for(iIndex = 1;iIndex <= iMaxIndex; ++iIndex)
{
if(astPollfd[iIndex].fd < 0)
{
continue;
}
if(0 != (astPollfd[iIndex].revents & (POLLRDNORM | POLLERR)))
{
if(0 > (iReadLen = read(astPollfd[iIndex].fd, szBuf, BUF_LEN_256)))
{
if(errno == ECONNRESET)
{
close(astPollfd[iIndex].fd);
astPollfd[iIndex].fd=-1;
}
else
{
return -1;
}
}
else if(0 == iReadLen)
{
close(astPollfd[iIndex].fd);
astPollfd[iIndex].fd=-1;
}
else
{
printf("%s",szBuf);
write(astPollfd[iIndex].fd, szBuf, iReadLen);
}
if(--iReady<=0)
{
break;
}
}
}
}
return 0;
}