static int
first_drv_open
(struct inode *inode, struct file *file)
![]()
{
printk("
first_drv_open\n
");
return 0;
}
static int
first_drv_read(struct file *filp, char __user *buff,
size_t count, loff_t *offp)
{
printk("
first_drv_read
\n
");
return 0;
}
static ssize_t
first_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
printk("
first_drv_write
\n
");
return 0;
}
将上面的函数告诉内核
a.需要定义一个结构体:
static struct
file_operations
first_drv_fops = {
.owner = THIS_MODULE, /* 这是一个宏,推向编译模块时自动创建的__this_module变量 */
.open =
first_drv_open
,
.read =
first_drv_read
,
.write =
first_drv_write
,
};
b. 注册,告诉内核
register_chrdev( major, "first_drv",
first_drv_fops ); //主设备号,名字,结构体名字
c.通过入口函数调用
register_chrdev,通过出口函数调用unregister_chrdev
int first_drv_init(void)
{
register_chrdev( 111, "first_drv",
first_drv_fops
);
return 0;
}
void first_drv_exit(void)
{
un
register_chrdev( 111, "first_drv"
);
}
d.修饰入口函数/出口函数
module_init(
first_drv_init
); //定义一个结构体,调用其中函数指针
指向入口函数
first_drv_init
module_exit(first_drv_exit);
下面是应用程序和驱动之间通过主设备号,file_optation结构体连接起来的示意图
编译上述驱动程序的Makefile
KERN_DIR = /work/system/linux-2.6.22.6 //编译使用的内核路径,内核要编译完成才可用
all:
make -C $(KERN_DIR) M=`pwd` modules //-C会转到
KERN_DIR目录中去,用目录中的Makefile编译。M=当前路径是什么。
modules是目标
clean:
make -C $(KERN_DIR) M=`pwd` modules clean
rm -rf modules.order
obj-m
+= myleds.o