在Linux系统中,字符设备是一种特殊的设备文件,它允许用户空间的程序通过文件系统接口与内核空间的设备驱动进行交互。字符设备通常用于那些只能顺序读写的设备,如键盘、鼠标、串口通信等。
register_chrdev
函数来注册你的字符设备,并指定一个主设备号和一个设备名称。/dev
目录下。可以使用mknod
命令来创建,指定设备的主设备号和次设备号。insmod
或modprobe
命令将你的内核模块加载到系统中。以下是一个简单的字符设备驱动程序的框架:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#define DEVICE_NAME "my_char_device"
#define CLASS_NAME "my_char_class"
static int major_number;
static struct class* my_char_class = NULL;
static struct device* my_char_device = NULL;
static int device_open(struct inode*, struct file*);
static int device_release(struct inode*, struct file*);
static ssize_t device_read(struct file*, char*, size_t, loff_t*);
static ssize_t device_write(struct file*, const char*, size_t, loff_t*);
static struct file_operations fops = {
.open = device_open,
.release = device_release,
.read = device_read,
.write = device_write,
};
static int __init my_char_init(void) {
major_number = register_chrdev(0, DEVICE_NAME, &fops);
if (major_number < 0) {
printk(KERN_ALERT "Failed to register a major number\n");
return major_number;
}
printk(KERN_INFO "Registered correctly with major number %d
", major_number);
my_char_class = class_create(THIS_MODULE, CLASS_NAME);
if (IS_ERR(my_char_class)) {
unregister_chrdev(major_number, DEVICE_NAME);
printk(KERN_ALERT "Failed to register device class\n");
return PTR_ERR(my_char_class);
}
printk(KERN_INFO "Device class registered correctly\n");
my_char_device = device_create(my_char_class, NULL, MKDEV(major_number, 0), NULL, DEVICE_NAME);
if (IS_ERR(my_char_device)) {
class_destroy(my_char_class);
unregister_chrdev(major_number, DEVICE_NAME);
printk(KERN_ALERT "Failed to create the device\n");
return PTR_ERR(my_char_device);
}
printk(KERN_INFO "Device class created correctly\n");
return 0;
}
static void __exit my_char_exit(void) {
device_destroy(my_char_class, MKDEV(major_number, 0));
class_unregister(my_char_class);
class_destroy(my_char_class);
unregister_chrdev(major_number, DEVICE_NAME);
}
module_init(my_char_init);
module_exit(my_char_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple character device driver");
MODULE_VERSION("0.1");
# 获取主设备号
major_number=$(grep my_char_device /proc/devices | awk '{print $1}')
# 创建设备文件
mknod /dev/my_char_device c $major_number 0
# 设置权限
chmod 666 /dev/my_char_device
字符设备通常用于那些需要直接与硬件交互的场景,例如:
如果你遇到具体的问题,比如设备无法正常工作或者驱动程序加载失败,可能需要检查内核日志(使用dmesg
命令)来获取更多信息,并根据错误信息进行调试。
领取专属 10元无门槛券
手把手带您无忧上云