?? drive.c
字號:
#include<linux/module.h>#include<linux/kernel.h>#include<linux/fs.h> MODULE_LICENSE("GPL");char mybuf[1024]="SCHOOL : HUST \nSEX : BOY \nNAME : Zhang Fuqiang \nNO. : 012004016415 \nTEACHER : Pang Lipin \n";int mychardrv_devnum; static int mychardrv_open(struct inode *inode,struct file*filp);static int mychardrv_read(struct file * filp,char *buf,size_t count, loff_t *f_pos);static int mychardrv_write(struct file * filp,const char *buf,size_t count,loff_t *ppos);static int mychardrv_release(struct inode* inode,struct file * filp);static loff_t mychardrv_lseek (struct file * file, loff_t offset,int orig);struct file_operations mychardrv_ops= { open: mychardrv_open, read: mychardrv_read, write: mychardrv_write, release: mychardrv_release, llseek:mychardrv_lseek,};int mychardrv_read(struct file * filp,char *buf,size_t count, loff_t *f_pos){ loff_t pos; pos=*f_pos; if(pos+count>1024) count=1024-pos; strncpy(buf,mybuf+pos,count); return count;}static int mychardrv_write(struct file * filp,const char *buf,size_t count,loff_t *ppos){ loff_t pos; pos=*ppos; if(pos+count>1024) count=1024-pos; strncpy(mybuf+pos,buf,count); return count;}int mychardrv_open(struct inode *inode,struct file*filp){ filp->f_op=&mychardrv_ops; return 0;}int mychardrv_release(struct inode* inode,struct file * filp){ return 0;}loff_t mychardrv_lseek (struct file * file,loff_t offset,int orig){ loff_t pos; pos = file->f_pos; switch (orig) { case 0: pos = offset; break; case 1: pos += offset; break; case 2: pos = 1024-offset; break; default: return -1; } return file->f_pos = pos;}int init_module(void) { int result; result=register_chrdev(0,"mychardrv",&mychardrv_ops); if(result<0) { printk("Unable to get devnum!!!!!\n"); return -1; } if(mychardrv_devnum==0) mychardrv_devnum=result; printk("Succeed in getting buffer!!!!\n"); return 0;}void cleanup_module(void) { unregister_chrdev(mychardrv_devnum,"mychardrv"); printk("Succeed in unload the moudle!!!\n");} /*加載之后通過命令 mknod /dev/mychardev c 254 0 來創建設備文件 設備號可通過命令 cat /proc/devices看到mychardrv所分配得到的設備號然后編寫測試程序打開該設備文件進行讀寫操作*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -