C
fops
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.
Exercise 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", ...).
Show example 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;
}
Test yourself
-
Match fops fields to trigger
- .open
- On device open
- .read
- On user read
- .write
- On user write
- .release
- On device close
-
When is the .read field of file_operations called?
- On device open
- On module load
- When the user reads
- On module remove
Show answer
When the user reads — .read fires when the user calls read().
-
Complete the fops .read assignment
.read = my_____,
Show answer
.read = my_read,
Next lesson: Summary - Driver basics