fops
- C course
- Expert
- Lesson 11/47
- 5 min
Learn the file_operations structure.
The file_operations structure
A character driver declares the operations it supports to user space through the file_operations structure, commonly shortened to fops.
Each field is a function pointer: .open, .read, .write, .release. When the user calls read(), the kernel calls the driver's .read pointer. Unsupported operations are left NULL; the kernel turns that into a suitable error. fops is registered with cdev_init and cdev_add. That lets user space use the /dev file like an ordinary file.
Defining fops
The fops struct is usually declared as a static const variable. Fields are assigned with .name = function; order does not matter.
Example: static const struct file_operations my_fops = { .open = my_open, .read = my_read, .write = my_write, .release = my_release };. This struct is passed as the second argument to cdev_init. The driver author must match each function's signature to the kernel prototype. A wrong signature causes a runtime error, not a compile error.
Practice Print fops fields
Define struct fops_entry { const char *name; const char *when; }. In main build a four-element array: {".open", "device open"}, {".read", "user reads"}, {".write", "user writes"}, {".release", "device close"}. Loop with for and print each with printf("%s -> %s\n", ...).
Starter code
#include <stdio.h>
// Define fops_entry struct
// Build a four-element array and print it with a for loop
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
struct fops_entry { const char *name; const char *when; };
int main(void) {
struct fops_entry fops[] = {
{".open", "device open"},
{".read", "user reads"},
{".write", "user writes"},
{".release", "device close"}
};
int n = sizeof(fops) / sizeof(fops[0]);
for (int i = 0; i < n; i++) {
printf("%s -> %s\n", fops[i].name, fops[i].when);
}
return 0;
}Expected output
.open -> device open .read -> user reads .write -> user writes .release -> device close
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match fops fields to trigger
| Term | Meaning |
|---|---|
.open |
On device open |
.read |
On user read |
.write |
On user write |
.release |
On device close |
2 When is the .read field of file_operations called?
- On device open
- On module load
- When the user reads Correct answer
- On module remove
Explanation: .read fires when the user calls read().
3 Complete the fops .read assignment
.read = my_____,
.read = my_read,
Explanation: The .read field is bound to my_read.