poll函数深入理解

1.看poll函数的调用逻辑

poll  应用的poll函数
	sys_poll
		do_sys_poll
			/*初始化一个poll_wqueues变量table*/
			poll_initwait(&table);
				__pollwait 将在驱动的poll函数里的poll_wait函数用到
				table ->pt-> qproc=__pollwait;
			do_poll(nfds, head, &table, timeout);
				for (; ;)
				{	
					do_pollfd
						driver->poll  驱动里面的poll函数
							poll_wait  会把当前进程挂载到等待队列
								__pollwait
							if (flag)
								mask |= POLLIN | POLLRDNORM
							return mask;
					poll_schedule_timeout 进入休眠状态
				}	

2.解释:进入休眠状态后,wake_up_interruptible会唤醒等待队列,唤醒后重新去执行for死循环,do_pollfd, 然后执行driver的poll函数中,会去设置一个条件变量flag,在wake_up_interruptible之前这个
条件变量就会设置为1,所以就会mask |= POLLIN | POLLRDNORM ; return mask; ,应用的poll
函数就会返回一个非0值。然后这时候我们再去read,因为read函数里面会有wait_event_interruptible等待事件,其flag值给1之后,就会唤醒,然后copy_to_user,让用户读到数据,这样就可以
实现对设备的无阻塞访问了。 poll的flag和wait_event_interruptible的flag可以用一个flag控制最方便。

*******
相关定义:
wait_queue_head_t: 定义一个等待队列头
	wait_queue_head_t detection_wait_head;
init_waitqueue_head:初始化等待队列
	init_waitqueue_head(&detection_wait_head);
等待事件:
wait_event_interruptible(detection_wait_head, condition)
condition = 0  ///休眠,
condition = 1  ///唤醒
condition为0的时候,wait_event_interruptible会让进程休眠,所谓休眠就是让出CPU 然后并不返回,其实就是阻塞
唤醒队列
wake_up_interruptible(&detection_wait_head);  用于唤醒挂在等待
队列上的进程,用wake_up_interruptible()唤醒后,wait_event_interruptible(wq, condition)宏,自身再检查“condition”这个条件以决定是返回还是继续休眠,真则返回,假则继续睡眠
poll_wait:它的作用就是把当前进程添加到wait参数指定的等待队列中
需要注意的是这个函数是不会引起阻塞的

你可能感兴趣的:(linux驱动)