温馨提示×

怎样编写linux驱动

小樊
62
2026-09-03 12:44:09
栏目: 智能运维

编写 Linux 驱动(通常指内核模块驱动)一般包括:准备环境 → 编写驱动代码 → 编写 Makefile → 编译 → 加载/测试 → 调试。下面我按新手可操作流程给你讲,并附带一个最简字符设备驱动示例。


一、准备环境

1. 安装编译环境

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

2. 确认内核版本

uname -r

驱动必须和当前运行内核版本一致。


二、Linux 驱动的基本分类

类型 说明
字符设备 最常见(如 LED、按键、串口)
块设备 硬盘、SD 卡
网络设备 网卡
平台设备 SoC 上的设备(ARM 常见)

新手建议从 字符设备驱动 学起。


三、最简单的字符设备驱动示例

1. 驱动代码:hello_drv.c

#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/init.h>
#include <linux/cdev.h>

static int major;
static char buf[100];

static int hello_open(struct inode *inode, struct file *file)
{
    printk("hello open\n");
    return 0;
}

static ssize_t hello_read(struct file *file, char __user *ubuf, size_t size, loff_t *off)
{
    copy_to_user(ubuf, buf, size);
    return size;
}

static ssize_t hello_write(struct file *file, const char __user *ubuf, size_t size, loff_t *off)
{
    copy_from_user(buf, ubuf, size);
    printk("write: %s\n", buf);
    return size;
}

static struct file_operations hello_fops = {
    .owner = THIS_MODULE,
    .open = hello_open,
    .read = hello_read,
    .write = hello_write,
};

static int __init hello_init(void)
{
    major = register_chrdev(0, "hello_drv", &hello_fops);
    printk("hello driver init, major=%d\n", major);
    return 0;
}

static void __exit hello_exit(void)
{
    unregister_chrdev(major, "hello_drv");
    printk("hello driver exit\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");

2. 编写 Makefile

obj-m += hello_drv.o

all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

3. 编译

make

生成:

hello_drv.ko

四、加载与测试驱动

1. 加载驱动

sudo insmod hello_drv.ko

2. 查看

dmesg | tail
ls /proc/devices

3. 创建设备节点

sudo mknod /dev/hello c 主设备号 0

4. 测试

echo "hello" > /dev/hello
cat /dev/hello

5. 卸载

sudo rmmod hello_drv

五、调试方法

  • dmesg:查看 printk 输出
  • printk 日志级别:
printk(KERN_INFO "info\n");
  • 使用 cat /proc/kmsg

六、进阶学习路线

  1. ✅ 字符设备(你已经会了)
  2. ✅ file_operations 详解
  3. ✅ platform_driver / device_tree
  4. ✅ 中断(request_irq)
  5. ✅ ioctl
  6. ✅ sysfs / proc
  7. ✅ 块设备 / 网络设备

七、推荐资料

  • 《Linux 设备驱动程序》(LDD3)
  • 内核源码:drivers/
  • 官方文档:Documentation/

如果你愿意,可以告诉我:

  • ✅ 你是 x86 还是 ARM(树莓派 / 开发板)
  • ✅ 想写 LED / 按键 / 串口 / 摄像头 / 网卡 哪种驱动

我可以给你针对具体硬件的驱动示例。

0 踩