⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 drive.c

📁 一个linux下字符设备驱动程序的编写例子
💻 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 + -