2021-05-12 14:32:11
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
#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 %cn",*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
相關文章