编写一个内核模块

#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.");

保存文件后,按以下步骤编译和测试模块:

  1. 创建 Makefile 文件:

    2. 在命令行中运行以下命令编译模块:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值