- 使用remap_pfn_range在内核层共享内存,完成mmp回调函数的编写。
- 默认动态分配设备号,允许以命令行方式指定设备号
- 使用cdev_add注册字符设备
- 使用device_create创建设备文件"/dev/demo0","/dev/demo1"
编译模块
#make
#sudo insmod sharedmem.ko
#cd /dev
#ls
有demo0,demo1
测试程序编译
#gcc user.c -o user
切换到root用户
#su root
#./user
root@imc:/home/imc/Documents/code/kernel-ethercat/sharedmem# ./user
buf 1 = cwd is in e308
buf 2 = cwd in house!
可以看到文件被成功打开。且共享内存的数据可以被读出与写入
#sudo rmmod sharedmem.ko
#dmesg
[13877.974141] sharemem: started
[13877.974212] sharemem: malloc finished;
[13883.140974] sharemem: file opened,minor=0,data=cwd is in e308
[13883.140983] sharemem: file opened,minor=1,data=cwd is in c412
[13883.140988] sharemem: mmap func run
[13883.140999] sharemem: mmap func runs fine,data=cwd is in e308
[13888.968110] sharemem: check if mmap func runs fine,mem_devp[0].data=cwd in house!
[13888.968111] sharemem: EXIT
简单头文件memdev.h
#ifndef _MEMDEV_H_
#define _MEMDEV_H_
#ifndef MEMDEV_MAJOR
#define MEMDEV_MAJOR 0 /*预设的mem的主设备号*/
#endif
#ifndef MEMDEV_NR_DEVS
#define MEMDEV_NR_DEVS 2 /*设备数*/
#endif
#ifndef MEMDEV_SIZE
#define MEMDEV_SIZE 4096
#endif
/*mem设备描述结构体*/
struct mem_dev
{
char *data;
unsigned long size;
};
#endif /* _MEMDEV_H_ */
内核模块程序sharedmem.c
//#define __KERNEL__
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm_types.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/io.h>
//#include <asm/system.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
<