写一个简单的字符设备驱动程序,给出示例代码
时间: 2023-03-12 09:09:30 浏览: 82
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>static struct cdev *my_cdev;
static dev_t my_dev;static int my_open (struct inode *inode, struct file *file)
{
printk("my_open\n");
return 0;
}static int my_release (struct inode *inode, struct file *file)
{
printk("my_release\n");
return 0;
}static struct file_operations my_ops = {
.owner = THIS_MODULE,
.open = my_open,
.release = my_release,
};static int __init my_init (void)
{
int ret; /* 注册设备号 */
ret = alloc_chrdev_region(&my_dev, 0, 1, "my_char_device");
if (ret < 0) {
printk("alloc_chrdev_region failed\n");
return ret;
} /* 初始化字符设备 */
my_cdev = cdev_alloc();
if (my_cdev == NULL) {
printk("cdev_alloc failed\n");
return -ENOMEM;
}
cdev_init(my_cdev, &my_ops); /* 添加字符设备 */
ret = cdev_add(my_cdev, my_dev, 1);
if (ret < 0) {
printk("cdev_add failed\n");
return ret;
} return 0;
}static void __exit my_exit (void)
{
/* 删除字符设备 */
cdev_del(my_cdev); /* 注销设备号 */
unregister_chrdev_region(my_dev, 1);
}module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");答案:我已经给出了一个简单的字符设备驱动程序的示例代码,它能够实现对设备的注册、初始化和添加等操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)