操作系统设备管理之驱动程序设计
程序员文章站
2022-09-02 20:46:57
实验目的:1.学习Linux环境下虚拟设备驱动程序的设计。2.学习如何将字符设备挂载到Liunx中,实验内容:1.编写一个虚拟字符设备的驱动程序模块demo.c,编译并通过2.将的到的设备模块挂载到Linux环境下。3.编写测试程序test.c对字符设备模块进行测试。4.卸载该模块。demo.c#include #include #include ...
实验目的:
1.学习Linux环境下虚拟设备驱动程序的设计。
2.学习如何将字符设备挂载到Liunx中,
实验内容:
1.编写一个虚拟字符设备的驱动程序模块demo.c,编译并通过
2.将的到的设备模块挂载到Linux环境下。
3.编写测试程序test.c对字符设备模块进行测试。
4.卸载该模块。
- demo.c
#include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> /* printk() */ #include <linux/fs.h> /* everything... */ #include <linux/errno.h> /* error codes */ #include <linux/types.h> /* size_t */ #include <linux/proc_fs.h> #include <linux/fcntl.h> /* O_ACCMODE */ #include <linux/poll.h> /* COPY_TO_USER */ #include <linux/version.h> #if LINUX_VERSION_CODE > KERNEL_VERSION(3,3,0) #include <asm/switch_to.h> #else #include<asm/system.h> #endif #define DEVICE_NAME "char" #define demo_MAJOR 300 #define demo_MINOR 0 #define MAX_BUF_LEN 20 static char drv_buf[32]; static int char_open(struct inode * inode,struct file*file) { //MOD_INC_USE_COUNT; sprintf(drv_buf,"device open sucess!\n"); printk("device open sucess!\n"); return 0; } static int char_release(struct inode *inode, struct file *filp) { //MOD_DEC_USE_COUNT; printk("device release\n"); return 0; } /********************************************************************/ static ssize_t char_read(struct file *filp, char *buffer, size_t count, loff_t *ppos) { if(count > MAX_BUF_LEN) count=MAX_BUF_LEN; copy_to_user(buffer, drv_buf,count); printk("user read data from driver\n"); return count; } static ssize_t char_write(struct file *filp,const char *buffer, size_t count, loff_t *ppos) { copy_from_user(drv_buf , buffer, count); printk("user write data to driver\n"); //your code here return count; } /******************************************************************/ //现在的版本没有ioctl函数,用unlocked_ioctl代替 static int char_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch(cmd){ case 1:{printk("ioctl runing \n"); printk("runing command 1 \n"); break;} case 2:{printk("ioctl runing \n"); printk("runing command 2 \n"); break;} default: printk("error cmd number\n");break; } return 0; } /*******************************************************************/ static struct file_operations char_fops = { owner: THIS_MODULE, write: demo_write, read: demo_read, ioctl: demo_unloced_ioctl,//注意 open: demo_open, release: demo_release, }; static int __init char_init(void) { int result; //SET_MODULE_OWNER(&demo_fops); result = register_chrdev(demo_MAJOR, "char", &char_fops); if (result < 0) return result; printk(DEVICE_NAME " initialized\n"); return 0; } //模块的出口函数 static void __exit demo_exit(void) { unregister_chrdev(char_MAJOR, "char"); printk(DEVICE_NAME " unloaded\n"); } module_init(demo_init); module_exit(demo_exit);
本文地址:https://blog.csdn.net/weixin_44029810/article/details/107776002
下一篇: 15个初学者必看的基础SQL查询语句