Linux 字符设备驱动实例
-
编写驱动程序,并将内核模块加载到内核中,等待被用户程序调用。
-
在控制台中借助第一步申请到的设备号,使用
mknod
命令创建一个设备节点,并拟一个设备名称。 -
在用户程序中,使用
open
打开第二步中的设备名称,通过设备节点间接控制驱动程序。
1. 驱动程序编写
cdev_driver.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("zz");
static dev_t devno;
#define KMAX_LEN 32
// 用户空间使用 open 函数时,触发该函数执行
static int demo_open(struct inode *ind, struct file *fp)
{
printk("demo open\n");
return 0;
}
// 用户空间使用 close 函数时,触发该函数执行
static int demo_release(struct inode *ind, struct file *fp)
{
printk("demo release\n");
return 0;
}
// 用户空间使用 read 函数时,触发该函数执行
static ssize_t demo_read(struct file *fp, char __user *buf, size_t size, loff_t *pos)
{
int rc;
char kbuf[KMAX_LEN] = "read test\n";
if (size > KMAX_LEN)
size = KMAX_LEN;
rc = copy_to_user(buf, kbuf, size);
if(rc < 0) {
return -EFAULT;
pr_err("copy_to_user failed!");
}
return size;
}
// 用户空间使用 write 函数时,触发该函数执行
static ssize_t demo_write(struct file *fp, const char __user *buf, size_t size, loff_t *pos)
{
int rc;
char kbuf[KMAX_LEN];
if (size > KMAX_LEN)
size = KMAX_LEN;
rc = copy_from_user(kbuf, buf, size);
if(rc < 0) {
return -EFAULT;
pr_err("copy_from_user failed!");
}
printk("%s", kbuf);
return size;
}
static struct file_operations fops = {
.open = demo_open,
.release = demo_release,
.read = demo_read,
.write = demo_write,
};
static struct cdev cd;
// // insmod 时,触发该函数执行
static int demo_init(void)
{
int rc;
rc = alloc_chrdev_region(&devno, 0, 1, "test"); // int alloc_chardev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name); 用于设备号未知,向系统动态申请未被占用的设备号的情况
if(rc < 0) {
pr_err("alloc_chrdev_region failed!");
return rc;
}
printk("MAJOR is %d\n", MAJOR(devno));
printk("MINOR is %d\n", MINOR(devno));
cdev_init(&cd, &fops); // void cdev_init(struct cdev *, struct file_operations *); 建立cdev和file_operations的连接
rc = cdev_add(&cd, devno, 1); // int cdev_add(struct cdev *, dev_t, unsigned); 完成字符设备的注册
if (rc < 0) {
pr_err("cdev_add failed!");
return rc;
}
return 0;
}
// rmmod 时执行该函数
static void demo_exit(void)
{
cdev_del(&cd); // 注销字符设备
unregister_chrdev_region(devno, 1); // 释放设备号
printk("rmmod ...\n");
return;
}
module_init(demo_init); // insmod 时,demo_init 会被调用
module_exit(demo_exit); // rmmod 时,demo_exit 会被调用
2. 应用程序编写
app.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int rc;
char buf[32];
int fd = open("/dev/test_chr_dev", O_RDWR);
if (fd < 0) {
printf("open file failed!\n");
return -1;
}
read(fd, buf, 32);
printf("%s", buf);
write(fd, "write test\n", 32);
close(fd);
return 0;
}
3. Makefile编写
ifneq ($(KERNELRELEASE),)
obj-m := cdev_driver.o
else
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
endif
all:
make -C $(KDIR) M=$(PWD) modules
clean:
make -C $(KDIR) M=$(PWD) clean
程序运行
1. make 编译驱动代码
2. gcc 编译用户程序代码
3. insmod 加载模块
4. dmesg 查看系统为设备分配的设备号
5. 使用 mknod 命令在系统中创建设备节点并运行程序
设备号与 dmesg 中查看的系统分配设备号一致,节点名称与用户程序中打开的设备文件名一致。