#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#define DEVICE_NAME "cap_driver"
#define BUF_LEN 80
static int major;
static char *msg;
static struct cdev cdev;
static int cap = 0;
module_param(cap, int, S_IRUGO);
static int device_open(struct inode *inode, struct file *file) {
msg = kmalloc(BUF_LEN, GFP_KERNEL);
if (!msg) {
return -ENOMEM;
}
try_module_get(THIS_MODULE);
return 0;
}
static int device_release(struct inode *inode, struct file *file) {
kfree(msg);
module_put(THIS_MODULE);
return 0;
}
static ssize_t device_read(struct file *filp, char *buffer, size_t length, loff_t *offset) {
int bytes_read = 0;
if (*msg == 0) {
return 0;
}
while (length && *msg) {
put_user(*(msg++), buffer++);
length--;
bytes_read++;
}
return bytes_read;
}
static ssize_t device_write(struct file *filp, const char *buff, size_t len, loff_t *off) {
int i;
if (len > BUF_LEN) {
len = BUF_LEN;
}
if (copy_from_user(msg, buff, len)) {
return -EFAULT;
}
for (i = 0; i < len; i++) {
if (cap && msg[i] >= 'a' && msg[i] <= 'z') {
msg[i] -= 32;
}
}
return len;
}
static struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
static int __init cap_driver_init(void) {
major = register_chrdev(0, DEVICE_NAME, &fops);
if (major < 0) {
printk(KERN_ALERT "Registering char device failed with %d\n", major);
return major;
}
cdev_init(&cdev, &fops);
cdev_add(&cdev, MKDEV(major, 0), 1);
printk(KERN_INFO "I was assigned major number %d. To talk to\n", major);
printk(KERN_INFO "the driver, create a dev file with\n");
printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, major);
return 0;
}
static void __exit cap_driver_exit(void) {
cdev_del(&cdev);
unregister_chrdev(major, DEVICE_NAME);
printk(KERN_INFO "Goodbye, world!\n");
}
module_init(cap_driver_init);
module_exit(cap_driver_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple character device driver that converts input to uppercase.");
保存文件后,按以下步骤编译和测试模块:
-
创建
Makefile
文件:2. 在命令行中运行以下命令编译模块: