Linux混杂字符设备,linux混杂字符


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

 

 

 1 #include <linux/module.h>
 2 #include <linux/init.h>
 3 #include <linux/io.h>
 4 #include <linux/miscdevice.h>
 5 #include <linux/fs.h>
 6 #include <asm/uaccess.h>
 7 
 8 unsigned int param=0;
 9 
10 static int my_open(struct inode *node,struct file *filep )
11 {
12     printk("Open my_open sucess!\n");
13     return 0;
14 }
15 static int my_read(struct file *filp,char __user *buf,size_t size,loff_t *pos)
16 {
17     printk("Read my_read sucess!\n");
18     param = 500;
19     copy_to_user(buf, &param, 4);
20     return 0;
21 }
22 
23 
24 struct file_operations my_miscdev_fops =
25 {     
26     .open = my_open,
27     .read = my_read,
28 };
29 
30 struct miscdevice my_miscdev = 
31 {
32     .minor = 200,
33     .name =  "my_miscdev",
34     .fops = &my_miscdev_fops,
35 };
36 static int my_miscdev_init(void)
37 {
38     int ret;
39     ret = misc_register(&my_miscdev);
40     if(ret != 0)
41         printk("miscdev register fail.\n!");
42     return 0;
43 
44 }
45 static void my_miscdev_exit(void)
46 {
47     misc_deregister(&my_miscdev);
48 
49 }
50 
51 MODULE_LICENSE("GPL");
52 
53 module_init(my_miscdev_init);
54 module_exit(my_miscdev_exit);

 

 

 1 #include <stdio.h>
 2 #include <sys/stat.h>
 3 #include <sys/types.h>
 4 #include <sys/ioctl.h>
 5 #include <fcntl.h>
 6 
 7 int main(char argc,char *argv[])
 8 {
 9     int fd;
10     int cmd;
11     int param = 0;
12     if(argc < 2)
13     {
14         printf("please enter the second param!\n");
15         return 0;    
16     }
17     cmd = atoi(argv[1]);
18     fd = open("/dev/my_miscdev",O_RDWR);
19     if(fd < 0)
20     {
21         printf("Open /dev/my_miscdev fail.\n");
22     }
23 
24     switch(cmd)
25     {
26         case 1:
27             printf("Second param is %c\n",*argv[1]);
28             read(fd, &param, 4);
29             printf("Read Param is %d.\n",param);
30             break;
31         default :
32             break;
33     }
34     close(fd);
35     return 0;
36 
37 }

 

 

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

 

相关内容