前面我们玩了linux中的select函数, 今天我们来介绍一个与之类似的函数, 作用就是做轮询检测, 建议先看select,  再看poll.  至于函数原型和返回值, 就没有必要单独说了, 网上一搜一大堆。

       直接上菜:

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <fcntl.h>
#include <fcntl.h> 
#include <sys/poll.h>  

#if 0
struct pollfd
{
	int fd;          //文件描述符
	short events;    //请求的事件
	short revents;   //返回的事件
};
#endif

int main()  
{
	pollfd fds[10];
	fds[0].fd = STDIN_FILENO;  // 标准输入描述符
	fds[0].events = POLLIN;    // 检测读

	int nfds = 1;              // 待监听的描述符的个数
	int timeoutMS = 5000;      // 毫秒
	int iRet = poll(fds, nfds, timeoutMS);  // 如果有描述集对应的事件发生,则触发立即返回, 否则就是超时返回
	if (iRet < 0)
	{  
	    printf("iRet is %d\n", iRet);
		return -1;
	}

	if (0 == iRet)
	{  
	    printf("time out\n");
		return -2;
	}

	char szBuf[1024] = {0};
	if (fds[0].revents & POLLIN) 
	{
		read(STDIN_FILENO, szBuf, sizeof(szBuf) - 1);  // 读取终端输入 
	}
	
	printf("str is [%s], strlen is %d\n", szBuf, strlen(szBuf));

    return 0;  
}  

       编译并运行, 然后别动, 5s后, 结果是: time out


       编译并运行, 然后再5s内输入abc, 结果是:

abc
str is [abc
], strlen is 4

      为什么在abc后换行了呢, 因为读取了enter的缘故。


      可见, poll和select大同小异, 可以对比理解。





本文转载:CSDN博客