多路IO(二)——select函数

本文通过一个具体的代码示例展示了如何使用select函数来监听标准输入和鼠标设备的活动。通过不断循环并设置超时时间,该示例可以及时响应用户的键盘和鼠标操作,并能够处理超时情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码演示:

select每次重新监听时需要重新设置“集合”和“超时时间”,因为每次select监听结束时会清空“集合”和“超时时间”。

int main(int argc, char *argv[])
{
	int ret = 0;	
 	int mousefd = 0;
	fd_set readfds;
	char buf[100] = {0};
	char buf1;
	struct timeval timeover;

	mousefd = open("/dev/input/mouse0", O_RDONLY);
	if (mousefd == -1) print_err("open /dev/input/mouse0 fail", __LINE__, errno);

	while(1)
	{
		timeover.tv_sec  = 3;
		timeover.tv_usec = 30;

		FD_ZERO(&readfds);//Empty file descriptor set
		FD_SET(0, &readfds);//Add the file descriptor 0 to the set
		FD_SET(mousefd, &readfds);//Add the file descriptor mousefd to the set
		
		//int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
		label:  ret = select(mousefd+1, &readfds, NULL, NULL, &timeover);
		if (ret == -1 && ret == EINTR) goto label;
		else if (ret == -1) print_err("select ", __LINE__, errno);
		/* If there is movement in the file descriptor set */
		else if (ret > 0) 
		{
			/* Determine which file descriptor it is */	
			/* TURE:1, false:0 */
			if (FD_ISSET(0, &readfds))
			{
				bzero(buf, sizeof(buf));	
				ret = read(0, buf, sizeof(buf));
				if (ret > 0) printf("%s\n", buf);
			}
			if (FD_ISSET(mousefd, &readfds))
			{
				bzero(&buf1, sizeof(buf1));	
				ret = read(mousefd, &buf1, sizeof(buf1));
				if (ret > 0) printf("%d\n", buf1);
			}
		}
		else if (ret == 0)
		{
			printf("time out\n");
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值