IO多路复用:select

出自朱有鹏老师的课堂

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
// 读取鼠标
int fd = -1;
int ret = -1;
char buf[200];
fd_set myset;
struct timeval tm;

fd = open("/dev/input/mouse1", O_RDONLY);	//fd打开鼠标,打开之后得到鼠标的文件描述符
if (fd < 0)
{
	perror("open:");
	return -1;
}
// 当前有两个fd,一个是fd一个是0
// 处理 myset
FD_ZERO(&myset);		// 全部清零
FD_SET(fd, &myset);		// 添加进去
FD_SET(0, &myset);

tm.tv_sec = 3;		//秒
tm.tv_usec = 0;		//微秒

ret = select(fd+1, &myset, NULL, NULL, &tm);	//select经过调用就会被阻塞,等待鼠标或者键盘的响应,如下:

if(ret < 0)				//出错了
{
	perror("select:");
	return -1;
}
else if(ret == 0)		//超时了
{
	printf("超时了.\n");
}
else					//大于0
{
	// 等到了其中的一路IO,然后去检测到底是哪一路的IO到了,然后处理她
	if(FD_ISSET(0, &myset))
	{
		// 处理键盘
		memset(buf, 0, sizeof(buf));
		//printf("before 键盘 read.\n");
		read(0, buf, 5);
		printf("键盘读出的内容是:[%s].\n", buf);
	}
	if(FD_ISSET(fd, &myset))
	{
		// 处理鼠标
		memset(buf, 0, sizeof(buf));
		//printf("before 鼠标 read.\n");
		read(fd, buf, 50);
		printf("鼠标读出的内容是:[%s].\n", buf);
	}

	
}
return 0;

}

猜你喜欢

转载自blog.csdn.net/weixin_43152566/article/details/90037449