Linux驱动实践编译内核驱动程序,简单的字符设备驱动

目录

一.配置环境并创建文件执行make

二.加载驱动

三.验证驱动

  • 配置环境并创建文件

1.准备开发环境,确保Ubuntu虚拟机已经安装了开发工具和内核头文件

sudo apt update

sudo apt install build-essential linux-headers-$(uname -r)

2.在Ubuntu终端中进入root

sudo -i

创建目录

mkdir mine

创建文件Makefile,并写入内容

nano Makefile

创建.c文件并写入驱动代码

nano hello2.c    //这里的文件名要和Makefile中的一样,就是第一行的obj-m += hello2.o

代码为:

// hello.c

#include <linux/init.h>

#include <linux/module.h>

#include <linux/fs.h>

#include <asm/uaccess.h>

MODULE_LICENSE("GPL");

MODULE_AUTHOR("Your Name");

MODULE_DESCRIPTION("A simple character device driver");

#define HELLO_SIZE 256

static char hello_buffer[HELLO_SIZE];

static int hello_open(struct inode *inode, struct file *filp);

static ssize_t hello_read(struct file *filp, char *buf, size_t count, loff_t *f_pos);

static ssize_t hello_write(struct file *filp, const char *buf, size_t count, loff_t *f_pos);

static int hello_release(struct inode *inode, struct file *filp);

static struct file_operations hello_fops = {

    .open = hello_open,

    .read = hello_read,

    .write = hello_write,

    .release = hello_release,

};

static int hello_major = 0;

static int __init hello_init(void) {

    int result;

    result = register_chrdev(hello_major, "hello", &hello_fops);

    if (result < 0) {

        printk(KERN_ALERT "hello: cannot obtain major number %d
", hello_major);

        return result;

    }

    if (hello_major == 0) {

        hello_major = result;

    }

    printk(KERN_INFO "Hello, character device driver loaded
");

    return 0;

}

static void __exit hello_exit(void) {

    unregister_chrdev(hello_major, "hello");

    printk(KERN_INFO "Goodbye, character device driver unloaded
");

}

static int hello_open(struct inode *inode, struct file *filp) {

    // Open logic, if needed

    return 0;

}

static ssize_t hello_read(struct file *filp, char *buf, size_t count, loff_t *f_pos) {

    // Read logic, if needed

    return 0;

}

static ssize_t hello_write(struct file *filp, const char *buf, size_t count, loff_t *f_pos) {

    ssize_t retval = 0;

    if (copy_from_user(hello_buffer, buf, count)) {

        return -EFAULT;

    }

    // Write logic here using data in hello_buffer

    return retval;

}

static int hello_release(struct inode *inode, struct file *filp) {

    // Release logic, if needed

    return 0;

}

module_init(hello_init);

module_exit(hello_exit);

显示样式为:

二.将两个文件放入创建好的mine目录中

cp Makefile mine

cp hello2.c mine

执行make

make

执行结果如上图,可以用ls 查看是否成功生成.ko文件

四.加载驱动模块

sudo insmod hello2.ko

检查驱动是否加载成功

dmesg

出现即为成功

五.输入内容

echo "Hello, World" > /dev/hello

确保在字符设备驱动中正确实现了写入操作。

再读取字符设备中的内容并输出到终端

cat /dev/hello2

成功!