ioctl
- C course
- Expert
- Lesson 3/47
- 5 min
Learn device control with ioctl.
What is ioctl?
ioctl (input/output control) is the system call that sends device-specific commands. While read and write move data, ioctl changes behavior.
For example, you read the terminal window size with the TIOCGWINSZ command. Setting disk speed or configuring a network interface also uses ioctl. Commands are declared in <sys/ioctl.h>. Each command encodes a number, direction and data size; the _IOR, _IOW, _IOWR macros build them.
Command macros and direction
ioctl commands are produced with _IOR(magic, nr, type). magic names the device family, nr the command number, and type the data structure.
The direction code says how data flows: _IOR reads from kernel to user, _IOW writes from user to kernel, _IOWR is bidirectional. Sending a wrong command yields ENOTTY. Driver authors define their command set with these macros so numbers do not collide. C programmers just use the predefined constants.
Practice Print ioctl commands
Define struct ioctl_cmd { const char *name; int code; }. In main create a three-element array: {"IOCTL_GET", 0}, {"IOCTL_SET", 1}, {"IOCTL_RUN", 2}. Loop with for and print each with printf("%s=%d\n", ...).
Starter code
#include <stdio.h>
// Define ioctl_cmd struct
// Build a three-element array and print it with a for loop
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
struct ioctl_cmd { const char *name; int code; };
int main(void) {
struct ioctl_cmd cmds[] = {
{"IOCTL_GET", 0},
{"IOCTL_SET", 1},
{"IOCTL_RUN", 2}
};
int n = sizeof(cmds) / sizeof(cmds[0]);
for (int i = 0; i < n; i++) {
printf("%s=%d\n", cmds[i].name, cmds[i].code);
}
return 0;
}Expected output
IOCTL_GET=0 IOCTL_SET=1 IOCTL_RUN=2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the ioctl command
int ret = ioctl(fd, ____, &win);
int ret = ioctl(fd, TIOCGWINSZ, &win);
Explanation: TIOCGWINSZ reads the terminal window size.
2 Match ioctl macros
| Term | Meaning |
|---|---|
_IOR |
Read from kernel |
_IOW |
Write to kernel |
_IOWR |
Bidirectional |
_IO |
No data |
3 What is ioctl used for?
- Sending network packets
- Reading a file
- Sending commands to a device Correct answer
- Allocating memory
Explanation: ioctl carries device-specific commands.