Linux kernel 中的轮询操作-select poll

本文介绍了轮询操作在应用程序和驱动程序中的实现原理及方法。详细解释了select()系统调用的功能,包括文件描述符集合的基本操作及监测函数的使用。并通过实例展示了如何使用轮询监测多个设备文件。

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

轮询操作:应用程序通常会使用select()系统调用查询是否可对设备进行无阻塞的访问。

该函数通过系统调用最终会引发设备驱动中的poll()函数被执行

该机制还可以实现一个用户进程对多个设备驱动文件的监测




轮询操作应用层接口函数介绍:

文件描述符集合的基本操作:

文件描述符集合的变量的定义

fd_set fds;

清空描述符集合

FD_ZERO(fd_set *set);

加入一个文件描述符到集合中

FD_SET(int fd, fd_set *set);

文件描述符集合的辅助操作:

从集合中清除一个文件描述符

FD_CLR(int fd, fd_set *set);

判断文件描述符是否被置位

FD_ISSET(int fd, fd_set *set);

返回非0,表示置位

(该文件描述集合中有文件可进行读写操作,或产

生错误)

#include <sys/select.h>

在应用程序中调用的文件描述符监测函数

int select(int numfds,

fd_set *readfds,

fd_set *writefds,

fd_set *exceptfds,

struct timeval *timeout);

参数1 numfds: 待监听中最大描述符值加一

参数2 readfds: 监听读操作的文件描述符集合

参数3 writefds: 监听写操作的文件描述符集合

参数4 exceptfds:监听异常处理的文件描述符集合

参数5 timeout: 监听等待超时退出select()

轮询操作驱动层接口函数介绍:

poll()函数:为file_operation成员之一
static unsigned int poll(struct file *file,
struct poll_table_struct *wait)
参数file:是文件结构指针
参数wait:轮询表指针,管理着一系列等待列表
注:以上两个参数是由内核传递给poll函数

//添加等待队列到wait参数指定的轮询列表中
void poll_wait(struct file *filp,
wait_queue_heat_t *wq, poll_table *wait);
poll_wait()将可能引起文件状态变化的进程添加到轮询列
表,由内核去监听进程状态的变化,不会阻塞进程
一旦进程有变化(wake_up),内核就会自动去调用poll()而poll()是返回给select()的,所以当进程被唤醒poll(应该将状态掩码返回给select(),从而select()退出阻塞。完成一次监测,poll函数被调用一次或两次
第一次为用户执行select函数时被执行
第二次调用poll为内核监测到进程的wake_up操作时或进程休眠时间到唤醒再或被信号唤醒时
poll函数返回的状态掩码
可读状态掩码
POLLIN:有数据可读
POLLRDNORM:有普通数据可读
POLLRDBAND:有优先数据可读
POLLPRI:有紧迫数据可读
可写状态掩码
POLLOUT:写数据不会导致阻塞
POLLWRNORM:写普通数据不会导致阻塞
POLLWRBAND:写优先数据不会导致阻塞

POLLMSG/SIGPOLL:消息可用

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/select.h>

int main()
{
	char *devname1 = "/dev/key8_eint";
	char *devname2 = "/dev/key2_eint";

	int fd1,fd2,fd_max;
	unsigned char key;
	int retval;
	
	fd1 = open(devname1, O_RDONLY);
	if (fd1 < 0){
		perror("open key_eint2_poll");
		exit(1);
	}
	
	fd2 = open(devname2, O_RDONLY);
	if (fd2 < 0){
		perror("open key_eint3_poll");
		exit(1);
	}
	
	while(1){
		fd_set rds;
		int ret;
		
		FD_ZERO(&rds);
		FD_SET(fd1, &rds);
		FD_SET(fd2, &rds);
		
		if(fd1 > fd2)
			fd_max = fd1;
		else
			fd_max = fd2;
	
		/*使用select监听设备描述符是否有变化*/
		retval = select(fd_max + 1, &rds, NULL,NULL, NULL);
		
		switch(retval){
			case -1 :
				perror("select");
				exit(1); 
				break;
			case 0 :
				printf("Timeout.\n"); 
				break;
			default:
				printf("the ret is %d\n",ret);
				if (FD_ISSET(fd1, &rds)) /*检查是否有数据可读*/
				{
					ret = read(fd1,&key, sizeof(key));
					printf("the key = %d\n",key);
				}
				else if (FD_ISSET(fd2, &rds)) /*检查是否有数据可读*/
				{
					ret = read(fd2,&key, sizeof(key));
					printf("the key = %d\n",key);
				}	
		}			
	}
	close(fd1);
	close(fd2);
}
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <mach/gpio.h>
#include <mach/regs-gpio.h>  

#include <linux/poll.h>  //poll_wait()

#define EINT_DEVICE_ID			1

#define DRIVER_NAME				"key8_eint"
#define err(msg) 				printk(KERN_ERR "%s: " msg "\n", DRIVER_NAME)
#define __debug(fmt, arg...)	printk(KERN_DEBUG fmt, ##arg)

#define GPH3CON					(unsigned long)(S5PV210_GPH3_BASE+ 0x00)
#define GPH3DAT					(unsigned long)(S5PV210_GPH3_BASE + 0x04)

#define GPH2UP					(unsigned long)(S5PV210_GPH2_BASE + 0x08)

static int major = 0;		
static int minor = 0;		
struct class *key_class;
static struct device *key_device;

/*定义等待队列头,该等待队列头属于该驱动程序*/
static wait_queue_head_t wait_queue;
static unsigned char key;

irqreturn_t buttons_interrupt(int irq, void *dev_id)
{	
	key = (unsigned int)dev_id;

	wake_up_interruptible(&wait_queue);			//唤醒等待队列
	return IRQ_HANDLED;
}

static void key_io_port_init(void)
{
	unsigned long reg_val;
	
	reg_val = readl(GPH3CON);
	reg_val &= ~((0x0f<<0) | (0x0f<<4));
	reg_val |= ((0x01<<0) | (0x01<<4));
	writel(reg_val, GPH3CON);

	reg_val = readl(GPH3DAT);
	reg_val &= ~((0x01<<0) | (0x01<<1));
	writel(reg_val, GPH3DAT);

	reg_val = readl(GPH2UP);
	reg_val &= ~(0x03<<8);
	reg_val |= 0x02<<8;
	writel(reg_val, GPH2UP);
}

static ssize_t key_read(struct file *filp, char *buf, size_t count, loff_t *f_pos)
{
	int key_num;
	int cpy_len;
	int retval;

	key_num = key;		//读取键值
	key = 0;
	cpy_len = min(sizeof(key_num), count);
	retval = copy_to_user(buf, &key_num, cpy_len);
	
	return (cpy_len - retval);
}

static unsigned int key_poll(struct file *file, struct poll_table_struct *wait)
{
	/*将当前进程添加到队列列表中,但不挂起该进程*/
	poll_wait(file, &wait_queue, wait);
	/*根据当前的键值返回适当的状态掩码*/
	return key==0 ? 0 : POLLIN | POLLRDNORM;
}

/* Driver Operation structure */
static struct file_operations key_fops = {
	.owner = THIS_MODULE,
	.read = key_read,
	.poll = key_poll,
};


static int __init key_eint_init(void)
{
	int retval;
	

	key_io_port_init();

	init_waitqueue_head(&wait_queue);			//初始化等待队列头
	
	retval = set_irq_type(IRQ_EINT(20),IRQ_TYPE_EDGE_FALLING);
	if(retval){
		err("IRQ_EINT20 set irq type failed");
		goto error;
	}
	
	retval = request_irq(IRQ_EINT(20), buttons_interrupt, IRQF_DISABLED, 
			"KEY1", (void *)EINT_DEVICE_ID);
	if(retval){
		err("request eint20 failed");
		goto error;
	}
	
	
	major = register_chrdev(major, DRIVER_NAME, &key_fops);
	if(major < 0){
		err("register char device fail");
		retval = major;
		goto error_register;
	}
	key_class=class_create(THIS_MODULE,DRIVER_NAME);
	if(IS_ERR(key_class)){
		err("class create failed!");
		retval =  PTR_ERR(key_class);
		goto error_class;
	}
	key_device=device_create(key_class,NULL, MKDEV(major, minor), NULL,DRIVER_NAME);
	if(IS_ERR(key_device)){
		err("device create failed!");
		retval = PTR_ERR(key_device);
		goto error_device;
	}
	__debug("register myDriver OK! Major = %d\n", major);
	return 0;

error_device:
	class_destroy(key_class);
error_class:
	unregister_chrdev(major, DRIVER_NAME);
error_register:
	free_irq(IRQ_EINT(20), (void *)EINT_DEVICE_ID);
error:
	return retval;
}

static void __exit key_eint_exit(void)
{
	//__debug("in key_eint_exit\n");
	
	free_irq(IRQ_EINT(20), (void *)EINT_DEVICE_ID);

	unregister_chrdev(major, DRIVER_NAME);
	device_destroy(key_class,MKDEV(major, minor));
	class_destroy(key_class);

	return;
}

module_init(key_eint_init);
module_exit(key_eint_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Eric");

 
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <mach/gpio.h>
#include <mach/regs-gpio.h>  

#include <linux/poll.h>  //poll_wait()

#define EINT_DEVICE_ID			2

#define DRIVER_NAME			"key2_eint"
#define err(msg) 					printk(KERN_ERR "%s: " msg "\n", DRIVER_NAME)
#define __debug(fmt, arg...)		printk(KERN_DEBUG fmt, ##arg)

#define GPH3CON					(unsigned long)(S5PV210_GPH3_BASE+ 0x00)
#define GPH3DAT					(unsigned long)(S5PV210_GPH3_BASE + 0x04)

#define GPH2UP					(unsigned long)(S5PV210_GPH2_BASE + 0x08)

static int major = 0;		
static int minor = 0;		
struct class *key_class;
static struct device *key_device;

/*定义等待队列头,该等待队列头属于该驱动程序*/
static wait_queue_head_t wait_queue;
static unsigned char key;

irqreturn_t buttons_interrupt(int irq, void *dev_id)
{	
	key = (unsigned int)dev_id;

	wake_up_interruptible(&wait_queue);			//唤醒等待队列
	return IRQ_HANDLED;
}

static void key_io_port_init(void)
{
	unsigned long reg_val;
	
	reg_val = readl(GPH3CON);
	reg_val &= ~((0x0f<<0) | (0x0f<<4));
	reg_val |= ((0x01<<0) | (0x01<<4));
	writel(reg_val, GPH3CON);

	reg_val = readl(GPH3DAT);
	reg_val &= ~((0x01<<0) | (0x01<<1));
	writel(reg_val, GPH3DAT);

	reg_val = readl(GPH2UP);
	reg_val &= ~(0x03<<6);
	reg_val |= 0x02<<6;
	writel(reg_val, GPH2UP);
}

static ssize_t key_read(struct file *filp, char *buf, size_t count, loff_t *f_pos)
{
	int key_num;
	int cpy_len;
	int retval;

	key_num = key;		//读取键值
	key = 0;
	cpy_len = min(sizeof(key_num), count);
	retval = copy_to_user(buf, &key_num, cpy_len);
	
	return (cpy_len - retval);
}

static unsigned int key_poll(struct file *file, struct poll_table_struct *wait)
{
	/*将当前进程添加到队列列表中,但不挂起该进程*/
	poll_wait(file, &wait_queue, wait);
	/*根据当前的键值返回适当的状态掩码*/
	return key==0 ? 0 : POLLIN | POLLRDNORM;
}

/* Driver Operation structure */
static struct file_operations key_fops = {
	.owner = THIS_MODULE,
	.read = key_read,
	.poll = key_poll,
};


static int __init key_eint_init(void)
{
	int retval;
	

	key_io_port_init();

	init_waitqueue_head(&wait_queue);			//初始化等待队列头
	
	retval = set_irq_type(IRQ_EINT(19),IRQ_TYPE_EDGE_FALLING);
	if(retval){
		err("IRQ_EINT20 set irq type failed");
		goto error;
	}
	
	retval = request_irq(IRQ_EINT(19), buttons_interrupt, IRQF_DISABLED, 
			"KEY1", (void *)EINT_DEVICE_ID);
	if(retval){
		err("request eint20 failed");
		goto error;
	}
	
	
	major = register_chrdev(major, DRIVER_NAME, &key_fops);
	if(major < 0){
		err("register char device fail");
		retval = major;
		goto error_register;
	}
	key_class=class_create(THIS_MODULE,DRIVER_NAME);
	if(IS_ERR(key_class)){
		err("class create failed!");
		retval =  PTR_ERR(key_class);
		goto error_class;
	}
	key_device=device_create(key_class,NULL, MKDEV(major, minor), NULL,DRIVER_NAME);
	if(IS_ERR(key_device)){
		err("device create failed!");
		retval = PTR_ERR(key_device);
		goto error_device;
	}
	__debug("register myDriver OK! Major = %d\n", major);
	return 0;

error_device:
	class_destroy(key_class);
error_class:
	unregister_chrdev(major, DRIVER_NAME);
error_register:
	free_irq(IRQ_EINT(19), (void *)EINT_DEVICE_ID);
error:
	return retval;
}

static void __exit key_eint_exit(void)
{
	//__debug("in key_eint_exit\n");
	
	free_irq(IRQ_EINT(19), (void *)EINT_DEVICE_ID);

	unregister_chrdev(major, DRIVER_NAME);
	device_destroy(key_class,MKDEV(major, minor));
	class_destroy(key_class);

	return;
}

module_init(key_eint_init);
module_exit(key_eint_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("eric");



### Select 函数的内核实现细节 `select` 是一种多路复用 I/O 的机制,在用户空间通过调用来监控多个文件描述符的状态变化。其核心功能是在内核中完成的,主要涉及以下几个方面: #### 文件描述符集的处理 在 `select` 调用过程中,内核会接收三个文件描述符集合:可读 (`readfds`)、可写 (`writefds`) 和异常条件 (`exceptfds`) 集合。这些集合由用户传递给系统调用,并在内核中被转换为适合操作的形式。 具体来说,内核会对传入的文件描述符集合进行解析并将其映射到内部数据结构上。这一步骤通常涉及到位图 (bitmap) 或类似的高效存储方式来记录哪些文件描述符处于监视状态[^2]。 #### 时间管理与超时控制 当调用者指定了一个非零的超时期限时,内核需要维护一个定时器以确保不会无限期阻塞。如果指定了 `NULL` 值,则表示该调用可以一直等待直到某个事件发生;而如果是正值,则会在一定时间内轮询一次所有感兴趣的文件描述符是否有活动迹象。 对于短时间间隔或者即时返回的需求(即 timeout 设置为 0),则不需要进入睡眠模式而是直接检查当前各句柄的状态即可快速响应请求。 #### 等待队列与唤醒机制 为了提高效率减少不必要的上下文切换开销,Linux 内核采用了一种基于等待队列的方法来实现 select 功能的核心部分——让进程休眠直至有相关联的任何一项资源变为可用状态为止。每当有一个新的输入/输出就绪通知到达时,相应的设备驱动程序就会负责将挂起在此处的所有线程叫醒以便它们重新评估自己的兴趣列表中的每一个成员是否满足条件。 一旦检测到至少存在某类感兴趣的变化情况之后,便立即将对应的结果反馈回去结束本次循环过程并将更新后的结果复制回用户空间供应用程序进一步分析使用。 ```c // Simplified pseudo-code of how a file descriptor might be checked within kernel space. if (file->f_op && file->f_op->poll) { mask |= file->f_op->poll(file, wait); } ``` 上述伪代码片段展示了如何利用各个打开对象自身的 poll 方法接口去查询各自支持的操作类型及其准备状况的信息。 ### 总结 综上所述,尽管表面上看只是简单的 API 接口定义,但实际上背后隐藏着复杂的逻辑链条贯穿整个操作系统架构层面的设计理念之中。从最底层硬件中断信号捕获一直到高层应用层面上展现出来的简洁易懂形式之间存在着许多中间环节共同协作才能达成最终目标效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eric_Xi_BJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值