Jul 10, 2024
/dev Directoryopen calls the opening method in the kernel module.write calls the write method in the kernel module.dev_number.c.#include <linux/fs.h>.Opening Function: Called when device file is opened.
static intdriver_openstruct inode, struct file0 on success, negative value on errorstatic int driver_open(struct inode *inode, struct file *file_instance) {
printk(KERN_INFO "open was called");
return 0;
}
Closing Function: Called when device file is closed.
static intdriver_closestruct inode, struct file0 on success, negative value on errorstatic int driver_close(struct inode *inode, struct file *file_instance) {
printk(KERN_INFO "close was called");
return 0;
}
Define Operations: Struct containing file operations.
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = driver_open,
.release = driver_close,
};
/proc/devices.
register_chrdev function.
int major_number = register_chrdev(90, "my_dev_number", &fops);
unregister_chrdev to free device number.
unregister_chrdev(90, "my_dev_number");
mknod command.
mknod /dev/my_device c 90 0
#include <stdio.h>
#include <fcntl.h>
int main() {
int fd = open("/dev/my_device", O_RDONLY);
if (fd < 0) {
perror("Failed to open device");
return 1;
}
close(fd);
return 0;
}
dmesg command.