制作第一个Linux驱动程序
发布日期:2021-05-08 23:07:57 浏览次数:21 分类:精选文章

本文共 2492 字,大约阅读时间需要 8 分钟。

编写一个简单的Linux驱动程序:从零开始到上线

编写一个Linux驱动程序,实现应用程序能通过系统调用,调用相应驱动函数,驱动程序中仅打印信息,不实现一些特定功能。

1. 创建一个驱动源文件 first_drv.c

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int major; static int first_drv_open(struct inode *inode, struct file *file) { printk("first_drv_open\n"); return 0; } static ssize_t first_drv_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { printk("first_drv_read\n"); return 0; } static ssize_t first_drv_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { printk("first_drv_read\n"); return 0; } struct file_operations first_drv_fileop = { .owner = THIS_MODULE, .open = first_drv_open, .read = first_drv_read, .write = first_drv_write, }; static int first_drv_init(void) { major = register_chrdev(0, "first_drv", &first_drv_fileop); return 0; } static void first_drv_exit(void) { unregister_chrdev(major, "first_drv"); } module_init(first_drv_init); module_exit(first_drv_exit); MODULE_LICENSE("GPL");

2. 创建一个编译驱动的Makefile

KERN_DIR = /home/book/self_learn/01_linux_develop/02_embedded_dir/02_kernel/linux-3.4.2
all:
make -C $(KERN_DIR) M=`pwd` modules
clean:
make -C $(KERN_DIR) M=`pwd` modules clean
rm -rf modules.orderobj-m
add -first_drv.o

3. 编译并加载驱动

make
cp first_drv.ko /lib/modules/$(shell uname -r)/updates/
depmod -a
insmod first_drv.ko

4. 手动创建设备节点

mknod /dev/first c 252 0

5. 编写测试程序

#include 
#include
#include
#include
int main(int argc, char **argv) {
int fd;
int val = 1;
fd = open("/dev/first", O_RDWR);
if (fd == -1) {
printf("can't open...\n");
exit(EXIT_FAILURE);
}
read(fd, &val, sizeof(val));
exit(EXIT_SUCCESS);
}

6. 优化驱动程序(自动创建设备节点)

static struct class *first_drv_class;
static struct class_device *first_drv_class_dev;
static int first_drv_init(void) {
first_drv_class = class_create(THIS_MODULE, "firstdrv");
if (!first_drv_class) {
return -1;
}
first_drv_class_dev = class_device_create(first_drv_class, NULL, MKDEV(major, 0), NULL, "firstdrv");
if (!first_drv_class_dev) {
return -1;
}
return 0;
}
static void first_drv_exit(void) {
class_device_unregister(first_drv_class_dev);
class_destroy(first_drv_class);
}

7. 测试驱动程序

通过以上步骤,您可以成功编写并测试一个简单的Linux驱动程序。驱动程序实现了文件操作的基本功能,并通过自动化的设备节点创建,简化了手动操作的复杂性。

上一篇:select函数
下一篇:rmmod: chdir(/lib/modules): No such file or directory 解决方法

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年05月08日 06时46分09秒