西北农林科技大学操作系统实验四(3)——设备管理之驱动程序设计

实验目的:

1.学习Linux环境下虚拟设备驱动程序的设计。
2.学习如何将字符设备挂载到Liunx中,

实验内容:

1.编写一个虚拟字符设备的驱动程序模块demo.c,编译并通过
2.将的到的设备模块挂载到Linux环境下。
3.编写测试程序test.c对字符设备模块进行测试。
4.卸载该模块。

  1. demo.c
#include 
#include 
#include        /* printk() */
#include                 /* everything... */
#include          /* error codes */
#include          /* size_t */
#include 
#include             /* O_ACCMODE */
#include              /* COPY_TO_USER */
#include 
#if LINUX_VERSION_CODE > KERNEL_VERSION(3,3,0)
#include 
#else
#include
#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);

你可能感兴趣的:(操作系统,实验)