当前位置:网站首页>Simplest character device driver
Simplest character device driver
2022-08-10 06:14:00 【Liu Shigang】
1.A device node needs to be created first
mknod /dev/xxx c 111 0
创建一个名字为xxx的字符设备, c表示字符设备, 主设备号是111, This device number is0.
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.Since the device number is not specified by our driver,默认是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;
}
/* written in this file5个字节,写入的内容是bufthe first five bytes in */
write(fd, buf, 5);
return 0;
}
4.测试效果
The test effect needs to be usedsudo dmesg来查看. 如下图所示:
边栏推荐
猜你喜欢
随机推荐
为什么游戏需要热更新
hanLP探索-语义距离计算的实现
剑指 Offer(第 2 版)7/4 1-4
The use of pointers from the exchange of two data values (C language implementation)
unity箭头控制物体移动
mysql连接报错:Cannot get a connection, pool error Timeout waiting for idle object
新建STM32F407ZG Keil5项目
链表、栈、队列
Tkinter 模块学习
【fiddler4】使用fiddler设置简单并发
屏幕后期处理之:Sobel算子实现边缘检测
浅谈游戏中3种常用阴影渲染技术(2):阴影锥
酸回收工艺原理
R language cluster analysis - code analysis
请亲们关注下我,谢谢了。
Easy to master Unity of eight prior to rendering
Unity对象池实现
21天学习挑战赛--字符串切割
开源游戏服务器框架NoahGameFrame(NF)服务器端环境搭建(二)
以STM32F103C6TA为例通过配置CubeMX实现GPIO输出完成点灯实例









