前言
创建一个简单的字符设备驱动程序。
? 本文命令的运行基本上都需要root权限,使用root账号,或者在命令前面加上sudo。
? 如果你使用ssh远程连接的服务器进行代码编写。那么不要在root用户下创建文件或者文件夹。这会导致你ssh连接vscode编写代码的权限问题。可以在普通用户创建好所有的文件,然后编写。
代码
驱动程序
hello_driver.c
#include <linux/types.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/cdev.h>
dev_t hello_devid;
struct cdev hello_cdev;
int hello_major = 0;
int hello_minor;
uint8_t kernel_buffer[1024] = {0};
static struct class *hello_class;
static int hello_world_open(struct inode * inode, struct file * file)
{
printk("hello_world_open\r\n");
return 0;
}
static int hello_world_release (struct inode * inode, struct file * file)
{
printk("hello_world_release\r\n");
return 0;
}
static ssize_t hello_world_read (struct file * file, char __user * buffer, size_t size, loff_t * ppos)
{
printk("hello_world_read size:%ld\r\n",size);
copy_to_user(buffer,kernel_buffer,size);
return size;
}
static ssize_t hello_world_write(struct file * file, const char __user * buffer, size_t size, loff_t *ppos)
{
printk("hello_world_write size:%ld\r\n",size);
copy_from_user(kernel_buffer,buffer,size);
return size;
}
static const struct file_operations hello_world_fops = {
.owner = THIS_MODULE,
.open = hello_world_open,
.release = hello_world_release,
.read = hello_world_read,
.write = hello_world_write,
};
static int __init hello_driver_init(void)
{
int ret;
printk("hello_driver_init\r\n");
alloc_chrdev_region(&hello_devid, 0, 1, "hello");
hello_major = MAJOR(hello_devid);
hello_minor = MINOR(hello_devid);
printk("hello driver major=%d,minor=%d\r\n",hello_major, hello_minor);
hello_cdev.owner = THIS_MODULE;
cdev_init(&hello_cdev, &hello_world_fops);
cdev_add(&hello_cdev, hello_devid, 1);
hello_class = class_create(THIS_MODULE,"hello_class");
device_create(hello_class,NULL,hello_devid,NULL,"hello"); /* /dev/hello */
return 0;
}
static void __exit hello_driver_cleanup(void)
{
printk("hello_driver_cleanup\r\n");
cdev_del(&hello_cdev);
unregister_chrdev_region(hello_devid, 1);
device_destroy(hello_class,hello_devid);
class_destroy(hello_class);
}
module_init(hello_driver_init);
module_exit(hello_driver_cleanup);
MODULE_LICENSE("GPL");
Makefile文件
KERNELDIR := /lib/modules/$(shell uname -r)/build
CURRENT_PATH := $(shell pwd)
obj-m := hello_driver.o
KBUILD_CFLAGS += -Wno-unused-result -Wno-unused-variable
build: kernel_modules
kernel_modules:
$(MAKE) ${CFLAGS} -C $(KERNELDIR) M=$(CURRENT_PATH) modules
$(CROSS_COMPILE)gcc -o test_app test_app.c
clean:
$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean
rm -rf test_app
测试程序
test_app.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
uint8_t buffer[512] = {0};
int