📄 demo_drv.c
字号:
#include <linux/config.h> //内核编译的配置文件
#include <linux/kernel.h> //调用printk()函数
#include <linux/init.h> //初始化模块
#include <linux/fs.h> //定义file_operations,file等结构体
#include <linux/devfs_fs_kernel.h> //调用注册及卸载函数
#include <linux/module.h> //模块驱动程序的头文件
#define Demo_MAJOR 98 //定义主设备号 创建设备进入点时要与此值一致
#define Demo_DEBUG
#define VERSION "Demo_Driver"
void showversion(void)
{
printk("*********************************************\n");
printk("\t %s \t\n", VERSION);
printk("*********************************************\n\n");
}
//static int Demo_temp_count = 0;
/* Demo设备的读操作接口函数 */
ssize_t Demo_read (struct file *file,char *buf,size_t count,loff_t *f_ops)
{
#ifdef Demo_DEBUG
printk ("Demo_read [ --kernel--]\n");
#endif
return count;
}
/* Demo设备的写操作接口函数 */
ssize_t Demo_write (struct file *file ,const char *buf,size_t count,loff_t *f_ops)
{
#ifdef Demo_DEBUG
printk ("Demo_write [ --kernel--]\n");
#endif
return count;
}
/* Demo设备的ioctl接口函数 */
int Demo_ioctl (struct inode *inode ,struct file *file,unsigned int cmd ,unsigned long data)
{
#ifdef Demo_DEBUG
printk ("Demo_ioctl [ --kernel--]\n");
#endif
return 0;
}
/* Demo设备的打开设备接口函数 */
int Demo_open (struct inode *inode ,struct file *file)
{
#ifdef Demo_DEBUG
printk ("Demo_open [ --kernel--]\n");
#endif
MOD_INC_USE_COUNT;
return 0;
}
/* Demo设备的关闭接口函数 */
int Demo_release (struct inode *inode,struct file *file)
{
#ifdef Demo_DEBUG
printk ("Demo_release [ --kernel--]\n");
#endif
MOD_DEC_USE_COUNT;
return 0;
}
/* Demo设备向系统注册操作功能,声明设备操作的功能接口函数 */
struct file_operations Test_ctl_ops ={
open: Demo_open,
read: Demo_read,
write: Demo_write,
ioctl: Demo_ioctl,
release: Demo_release,
};
/* 系统初始化 */
static int __init HW_Test_CTL_init(void)
{
int ret=-ENODEV;
ret=devfs_register_chrdev(Demo_MAJOR, "demo_drv", &Test_ctl_ops);
showversion();
if( ret < 0 )
{
printk (" Demo_module failed with %d\n [ --kernel--]", ret);
return ret;
}
else
{
printk(" Demo_driver register success!!! [ --kernel--]\n");
}
printk("\n...............\nret =%x\n...............\n", ret );
return ret;
}
static int __init Demo_Test_CTL_init(void)
{
int ret=-ENODEV;
#ifdef Demo_DEBUG
printk ("Demo_Test_CTL_init [ --kernel--]\n");
#endif
ret=HW_Test_CTL_init();
if(ret)
return ret;
return 0;
}
/* 系统卸载 */
static void __exit cleanup_Test_ctl(void)
{
#ifdef Demo_DEBUG
printk ("cleanup_INT_ctl [ --kernel-- ]\n");
#endif
devfs_unregister_chrdev(Demo_MAJOR, "demo_drv" );
}
/* 驱动程序版本及GPL协议证书信息 */
MODULE_DESCRIPTION("simple int driver module");
MODULE_LICENSE("GPL");
/* 内核模块入口,相当于main()函数,完成模块初始化*/
module_init(Demo_Test_CTL_init);
/* 卸载时调用的函数入口,完成模块卸载 */
module_exit(cleanup_Test_ctl);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -