Linux混杂字符设备
混杂设备驱动模型
混杂设备概念
在Linux系统中,存在一类字符设备,它们拥有相同的主设备号(10),但次设备号不同,我们称这类设备为混杂设备(miscdevice)。所有的混杂设备形成一个链表,对设备访问时内核根据次设备号查找到相应的混杂设备。
1.设备描述
Linux中使用struct miscdevice来描述一个混杂设备。
struct miscdevice {
int minor; /* 次设备号*/
const char *name; /* 设备名*/
const struct file_operations *fops; /*文件操作*/
struct list_head list;
struct device *parent;
struct device *this_device;
};
2.设备注册
Linux中使用misc_register函数来注册一个混杂设备驱动。
int misc_register(struct miscdevice * misc)
先写一个内核态数据与用户态数据互传的例子及APP
手动安装步骤:
Insmod my_char_dev.ko
不需要再安装设备节点
然后是测试app
./my_char_dev_app 1
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
unsigned int param=0;
static int my_open(struct inode *node,struct file *filep )
{
printk(“Open my_open sucess!\n”);
return 0;
}
static int my_read(struct file *filp,char __user *buf,size_t size,loff_t *pos)
{
printk(“Read my_read sucess!\n”);
param = 500;
copy_to_user(buf, ¶m, 4);
return 0;
}
struct file_operations my_miscdev_fops =
{
.open = my_open,
.read = my_read,
};
struct miscdevice my_miscdev =
{
.minor = 200,
.name = “my_miscdev”,
.fops = &my_miscdev_fops,
};
static int my_miscdev_init(void)
{
int ret;
ret = misc_register(&my_miscdev);
if(ret != 0)
printk(“miscdev register fail.\n!”);
return 0;
}
static void my_miscdev_exit(void)
{
misc_deregister(&my_miscdev);
}
MODULE_LICENSE(“GPL”);
module_init(my_miscdev_init);
module_exit(my_miscdev_exit);
——————————————————————–
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <fcntl.h>
int main(char argc,char *argv[])
{
int fd;
int cmd;
int param = 0;
if(argc < 2)
{
printf(“please enter the second param!\n”);
return 0;
}
cmd = atoi(argv[1]);
fd = open(“/dev/my_miscdev”,O_RDWR);
if(fd < 0)
{
printf(“Open /dev/my_miscdev fail.\n”);
}
switch(cmd)
{
case 1:
printf(“Second param is %c\n”,*argv[1]);
read(fd, ¶m, 4);
printf(“Read Param is %d.\n”,param);
break;
default :
break;
}
close(fd);
return 0;
}
—————————————-
1 obj-m := my_miscdev.o
2 KDIR := /home/win/dn377org/trunk/bcm7252/linux/
3 all:
4 make -C $(KDIR) M=$(PWD) modules CROSS_COMPILE=arm-linux- ARCH=arm
5 clean:
6 rm -f *.ko *.o *.mod.o *.mod.c *.symvers *.bak *.order
本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-02/128598.htm