当前位置:网站首页>最简单的字符设备驱动
最简单的字符设备驱动
2022-08-10 05:37:00 【刘十彡】
1.需要先创建设备节点
mknod /dev/xxx c 111 0
创建一个名字为xxx的字符设备, c表示字符设备, 主设备号是111, 此设备号是0。
2. 驱动程序
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/module.h>
static int first_drv_open(struct inode *inodep, struct file *filep)
{
printk("open\n");
return 0;
}
static ssize_t first_drv_write(struct file *filep, const char __user *buf,size_t len, loff_t *ppos)
{
printk("write\n");
return 0;
}
static const struct file_operations first_drv_file_operation = {
.owner = THIS_MODULE,
.open = first_drv_open,
.write = first_drv_write,
};
static int __init first_drv_init(void)
{
register_chrdev(111,"first_drv", &first_drv_file_operation);
printk("first_drv_init\n");
return 0;
}
static void __exit first_drv_exit(void)
{
//注册字符设备 主设备号是111.从设备号因为我们驱动程序没指定所以,默认是0.
unregister_chrdev(111,"first_drv_exit");
printk("first_drv_exit\n");
}
module_init(first_drv_init);
module_exit(first_drv_exit);
MODULE_LICENSE("GPL");
3. 应用程序,调用驱动程序
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
char buf[10];
/* 以可读可写方式打开/dev/目录下的xxx设备,open的返回值是一个文件描述符 */
int fd = open("/dev/xxx", O_RDWR);
if(fd < 0) /* 文件描述符小于0表示打开文件失败 */
{
printf("open /dev/xxx fail\n");
return -1;
}
/* 该文件中写入5个字节,写入的内容是buf中的前五个字节 */
write(fd, buf, 5);
return 0;
}
4.测试效果
测试效果需要使用sudo dmesg来查看. 如下图所示:
边栏推荐
猜你喜欢
开源游戏服务器框架NoahGameFrame(NF)客户端环境搭建(三)
Flutter的生命周期
Convolutional Neural Network (CNN) for Clothing Image Classification
LeetCode 100. The same tree (simple)
【从零设计 LaTex 模板】1. 一些基础知识
2021-04-15 jacoco代码覆盖率统计和白盒测试
STM32单片机OLED经典2048游戏单片机小游戏
STM32F407ZG 看门狗 IWDG & WWDG
STM32单片机手机APP蓝牙高亮RGB彩灯控制板任意颜色亮度调光
深度学习阶段性报告(一)
随机推荐
解决错误 Could not find method leftShift() for arguments
开源游戏服务器框架NoahGameFrame(NF)简介(一)
浅谈《帧同步网络游戏》之“框架”实现思路
I don't like my code
I don't like my code
【从零设计 LaTex 模板】1. 一些基础知识
【简易笔记】PyTorch官方教程简易笔记 EP1
以STM32F103C6T6为例通过配置CubeMX实现EXIT外部中断
常用模块封装-pymysql、pymongo(可优化)
Gradle学习(二)Groovy
pytorch-11. Convolutional Neural Network (Advanced)
详解 Hough 变换(上)基本原理与直线检测
ASP.NET有关于文件上传、下载、全选、删除选中重要干货(亲测有效)
接口自动化2.0
STM32F407ZG PWM
深度学习阶段性报告(一)
Unity中Xml简介以及通过脚本读取Xml文本中的内容
浅谈游戏中3种常用阴影渲染技术(1):平面阴影
酸回收工艺原理
ASP.NET连接SQL Server的步骤