请给我一个2.6版本内核的字符设备注册的简单示例
时间: 2023-07-31 11:10:13 浏览: 52
好的,以下是一个2.6版本内核的字符设备注册的简单示例:
```c
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#define DEVICE_NAME "example_device"
#define CLASS_NAME "example_class"
static dev_t dev_num;
static struct cdev cdev;
static struct class *dev_class;
static char msg[256];
static int example_open(struct inode *inode, struct file *file) {
printk(KERN_INFO "Open example device\n");
return 0;
}
static int example_release(struct inode *inode, struct file *file) {
printk(KERN_INFO "Close example device\n");
return 0;
}
static ssize_t example_read(struct file *file, char __user *buf, size_t len, loff_t *offset) {
ssize_t ret = simple_read_from_buffer(buf, len, offset, msg, strlen(msg));
printk(KERN_INFO "Read %zd bytes from example device\n", ret);
return ret;
}
static ssize_t example_write(struct file *file, const char __user *buf, size_t len, loff_t *offset) {
ssize_t ret = simple_write_to_buffer(msg, sizeof(msg), offset, buf, len);
printk(KERN_INFO "Write %zd bytes to example device\n", ret);
return ret;
}
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = example_open,
.release = example_release,
.read = example_read,
.write = example_write,
};
static int __init example_init(void) {
int ret;
ret = alloc_chrdev_region(&dev_num, 0, 1, DEVICE_NAME);
if (ret < 0) {
printk(KERN_ERR "Failed to allocate device number\n");
return ret;
}
cdev_init(&cdev, &fops);
cdev.owner = THIS_MODULE;
ret = cdev_add(&cdev, dev_num, 1);
if (ret < 0) {
printk(KERN_ERR "Failed to add cdev\n");
unregister_chrdev_region(dev_num, 1);
return ret;
}
dev_class = class_create(THIS_MODULE, CLASS_NAME);
if (IS_ERR(dev_class)) {
printk(KERN_ERR "Failed to create device class\n");
cdev_del(&cdev);
unregister_chrdev_region(dev_num, 1);
return PTR_ERR(dev_class);
}
device_create(dev_class, NULL, dev_num, NULL, DEVICE_NAME);
printk(KERN_INFO "Example device registered\n");
return 0;
}
static void __exit example_exit(void) {
device_destroy(dev_class, dev_num);
class_destroy(dev_class);
cdev_del(&cdev);
unregister_chrdev_region(dev_num, 1);
printk(KERN_INFO "Example device unregistered\n");
}
module_init(example_init);
module_exit(example_exit);
MODULE_LICENSE("GPL");
```
这个示例代码实现了一个名为 `example_device` 的字符设备,支持打开、关闭、读取和写入操作。在模块初始化时,它会分配一个设备号,注册字符设备,并创建一个名为 `example_class` 的设备类。在模块退出时,它会注销字符设备,并释放相关资源。