IO多路复用:select

本文展示了一个使用C语言和Linux系统调用select监听鼠标和键盘输入的示例。通过打开设备文件/dev/input/mouse1并设置文件描述符集,程序能够同时监听来自鼠标和键盘的输入,并在接收到输入时分别读取并打印内容。

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

出自朱有鹏老师的课堂

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值