阻塞操作是指在执行I/O操作时,若不能获得资源,则进程睡眠直到满足可操作的条件时再进行操作。非阻塞操作是指是执行I/O操作时,如果设备没有准备好,立即返回。
在Linux中,阻塞访问是通过等待队列(wait queue)来实现的。下面先简单介绍一下。
(一)等待队列的实现方式
In Linux, a wait queue is managed by means of a “wait queue head,” a structure of
type wait_queue_head_t, which is defined in <linux/wait.h>. A wait queue head can be defined and initialized statically with:
DECLARE_WAIT_QUEUE_HEAD(name);
or dynamicly as follows:
wait_queue_head_t my_queue;
init_waitqueue_head(&my_queue);
(二)简单的阻塞机制
When a process sleeps, it does so in expectation that some condition will become
true in the future. As we noted before, any process that sleeps must check to be sure
that the condition it was waiting for is really true when it wakes up again(these macros had done it inside). The simplest way of sleeping in the Linux kernel is a macro called wait_event (with a few
variants); it combines handling the details of sleeping with a check on the condition
a process is waiting for. The forms of wait_event are:
wait_event(queue, condition)
wait_event_interruptible(queue, condition)
wait_event_timeout(queue, condition, timeout)
wait_event_interruptible_timeout(queue, condition, timeout)
and
void wake_up(wait_queue_head_t *queue);
void wake_up_interruptible(wait_queue_head_t *queue);
在一般情况下,依靠这种简单的睡眠与唤醒机制就可以完成驱动的阻塞与非阻塞处理。