Blocking and Non-blocking I/O¶
A Linux driver should define what happens when user space tries to read data while no event or data is available.
The usual behavior is:
- blocking mode: sleep until data becomes available
- non-blocking mode: return
-EAGAIN
Read Path Model¶
read()
↓
check event queue
↓
if data available: copy_to_user()
↓
if no data and O_NONBLOCK: return -EAGAIN
↓
if no data and blocking: wait_event_interruptible()
Why This Matters¶
This behavior allows the same driver to support different user-space styles:
| User-space Style | Driver Behavior |
|---|---|
Simple blocking read() |
Sleep until data is ready |
O_NONBLOCK loop |
Return -EAGAIN if empty |
poll / epoll |
Report readiness only when data is available |
Driver-Side Checks¶
if (queue_empty(dev)) {
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
ret = wait_event_interruptible(dev->wq, !queue_empty(dev));
if (ret)
return ret;
}
Common Pitfalls¶
Warning
Do not return 0 when no data is available unless the driver intentionally reports EOF. For non-blocking device reads, -EAGAIN is usually the correct result.
Warning
Always re-check the condition after waking up. Wakeups can be interrupted or spurious.