mychar.c
来自「字符驱动程序」· C语言 代码 · 共 82 行
C
82 行
#include <asm/segment.h>#include <asm/uaccess.h>#include <linux/config.h>#include <linux/errno.h>#include <linux/fs.h>#include <linux/mm.h>#include <linux/module.h>#include <linux/types.h>#include <linux/version.h>#define __NO_VERSION__ //版本信息unsigned int regist=0; //注册标志unsigned int count=0; //用户数目static ssize_t chopen(struct file *file, const char *buf, size_t length, loff_t *f_pos){ count++; //增加用户数目 printk("The character device 'mychar' has been open!\n"); return 0;}static ssize_t chread(struct file *file,const char *buf,size_t length,loff_t *f_pos){ int i,j; if(!count) return 0; printk("Reading...\n"); for(i=length,j=0; i>0; i--){ __put_user(++j,buf); //向用户传送数据 buf++; } printk("Finish!\n"); return 1;}static ssize_t chwrite(struct file *file, const char *buf, size_t length, loff_t *f_pos){ char c; int i; if(!count) return 0; printk("Writing...\n"); for(i=0; i<length; i++){ __get_user(c, buf); //从用户接收数据 printk("%c ",c); buf++; } printk("\nFinish!\n"); return 1;}static ssize_t chrelease(struct file *file, const char *buf, size_t length, loff_t *f_pos){ count--; //减少用户数目 printk("The character device 'mychar' has been closed!\n"); return 0;}struct file_operations mychar_fops={ open: chopen, //打开字符设备 read: chread, //读取字符设备 write: chwrite, //写入字符设备 release: chrelease //关闭字符设备 }; //字符设备结构int init_module(void){ int num; num=register_chrdev(0, "mychar", &mychar_fops); //注册设备 if(num<0){ printk(KERN_INFO "Regist failed!\n"); //注册失败 return num; } if(!regist) regist=num; //修改注册标志 return 0;}void cleanup_module(void){ unregister_chrdev(regist,"mychar"); //卸载设备}MODULE_LICENSE("GPL");MODULE_AUTHOR("BECKHAM"); //版权信息
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?