Blocking I/O
One problem that might arise with read is what to do when there’s no data yet, but we’re not at end-of-file.
The default answer is “go to sleep waiting for data.” This section shows how a process is put to sleep, how it is awakened, and how an application can ask if there is data without just blindly issuing a read call and blocking. We then apply the same concepts to write.
As usual, before we show actual code, we’ll explain a few concepts.
Going to Sleep and Awakening
Whenever a process must wait for an event (such as the arrival of data or the termination of a process), it should go to sleep. Sleeping causes the process to suspend execution, freeing the processor for other uses. At some future time, when the event being waited for occurs, the process will be woken up and will continue with its job. This section discusses the 2.4 machinery for putting a process to sleep and waking it up. Earlier versions are discussed in Section 5.7 later in this chapter.
There are several ways of handling sleeping and waking up in Linux,
each suited to different needs. All, however, work with the same basic
data type, a wait queue (wait_queue_head_t). A
wait queue is exactly that—a queue of
processes that are waiting for an event. Wait queues are declared and
initialized as follows:
wait_queue_head_t my_queue; init_waitqueue_head (&my_queue);
When a wait queue is declared statically (i.e., not as an automatic variable of a procedure or as part of a dynamically-allocated ...