Non-blocking input
- C course
- Advanced
- Lesson 45/83
- 5 min
Learn to read non-blocking input.
Non-blocking input
Non-blocking input prevents read from waiting when there is no data. You put the descriptor into non-blocking mode with fcntl(fd, F_SETFL, O_NONBLOCK). After this, read returns -1 if there is no data and errno becomes EAGAIN.
This is a foundational pattern for games and interactive apps. Once STDIN_FILENO is non-blocking, you can read in a loop; if there is no data, you do other work. For testing, printf("nonblock: 1\n") is enough; it is deterministic. In real apps, read is called in a loop and EAGAIN is checked.
Handling EAGAIN
A non-blocking read returns -1 if there is no data. The errno value becomes EAGAIN (or EWOULDBLOCK). This is not an error; it just signals that there is no data right now.
The correct pattern: ssize_t n = read(fd, buf, sizeof(buf)); if (n < 0 && errno == EAGAIN) { /* no data, continue */ }. So the program does other work instead of waiting when there is no data. For testing, just calling fcntl and printf is enough; the real read loop is environment-dependent. The output stays deterministic.
Practice Set non-blocking mode
Set the descriptor to non-blocking mode with fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);. Print the state with printf("nonblock: 1\n");.
Starter code
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
// Set descriptor to non-blocking mode
// Print state
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(void) {
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
printf("nonblock: 1\n");
return 0;
}Expected output
nonblock: 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 fcntl call
fcntl(STDIN_FILENO, F_SETFL, ____);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
Explanation: O_NONBLOCK puts the descriptor into non-blocking mode.
2 Match non-blocking concepts
| Term | Meaning |
|---|---|
fcntl |
Sets flag |
O_NONBLOCK |
Non-blocking |
EAGAIN |
No data |
F_SETFL |
Flag command |
3 What does non-blocking read return when there is no data?
- -1 with errno EAGAIN Correct answer
- Waits forever
- 0
- EOF
Explanation: -1 is returned and errno is EAGAIN; not an error.