多路IO(二)——select函数

代码演示:

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`select` 函数是一种 I/O 多路复用的机制,用于同时监听多个文件描述符的状态变化。它可以使用单个系统调用同时监视多个文件描述符,并在有一个或多个文件描述符就绪时通知应用程序。 `select` 函数的原型如下: ```c #include <sys/select.h> int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); ``` 参数说明: - `nfds`:待监视的最大文件描述符加 1。 - `readfds`:可读文件描述符集合。 - `writefds`:可写文件描述符集合。 - `exceptfds`:异常条件文件描述符集合。 - `timeout`:超时时间,如果为 `NULL` 则为阻塞模式,即一直等待直到有文件描述符就绪;如果为零时间(`tv_sec` 和 `tv_usec` 均为 0),则为非阻塞模式,即立即返回;否则为指定超时时间。 `select` 函数的返回值表示就绪文件描述符的数量,如果返回值为 0,则表示超时;如果返回值为 -1,则表示出错。 使用 `select` 函数的一般流程如下: 1. 初始化需要监视的文件描述符集合。 2. 调用 `select` 函数等待文件描述符就绪。 3. 检查返回值确定哪些文件描述符已经就绪。 4. 处理就绪的文件描述符。 5. 重复上述步骤。 需要注意的是,`select` 函数有一些限制,比如只能监视的文件描述符数量有限,一般为 1024 或更小。此外,在某些平台上,使用 `select` 函数可能会有性能上的限制,可以考虑使用更高效的机制,如 `poll` 或 `epoll`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值