I am finally writing my first kernel module, a tiny misc device that returns a string. It works, and I want to understand why it works.
#include <linux/module.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
static ssize_t hello_read(struct file *f, char __user *buf,
size_t len, loff_t *off)
{
static const char msg[] = "hello\n";
return simple_read_from_buffer(buf, len, off, msg, sizeof(msg) - 1);
}
static const struct file_operations hello_fops = {
.owner = THIS_MODULE,
.read = hello_read,
};
static struct miscdevice hello_dev = {
.minor = MISC_DYNAMIC_MINOR,
.name = "hello",
.fops = &hello_fops,
};
module_misc_device(hello_dev);
MODULE_LICENSE("GPL");
cat /dev/hello prints hello. But where does the kernel decide "this read() goes to hello_read"? And what is that off pointer for? I tried returning len every time and cat printed forever.