//内核模块测试程序
#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/mm.h>
static unsigned long p = 0;
static int __init shao_init(void)
{
//分配共享内存(一个页面)
p = __get_free_pages(GFP_KERNEL, 0);
SetPageReserved(virt_to_page(p));
printk("<1> p = 0x%08x/n", p);
//在共享内存中写上一个字符串
strcpy(p, "Hello world!/n");
return 0;
}
static void __exit shao_exit(void)
{
ClearPageReserved(virt_to_page(p));
free_pages(p, 0);
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kuanish");
MODULE_DESCRIPTION("mmap test");
module_init(shao_init);
module_exit(shao_exit);
//用户态测试程序
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#define PAGE_SIZE (4*1024)
#define PAGE_OFFSET 0xc0000000
#define KERNEL_VIRT_ADDR 0xc5e3c000 //此处地址即为内核模块打印的地址p,动态的不固定,需要自行修改
int main()
{
char *buf;
int fd;
unsigned long phy_addr;
fd=open("/dev/mem",O_RDWR);
if(fd == -1)
perror("open");
phy_addr=KERNEL_VIRT_ADDR - PAGE_OFFSET;
buf=mmap(0, PAGE_SIZE,
PROT_READ|PROT_WRITE, MAP_SHARED,
fd, phy_addr);
if(buf == MAP_FAILED)
perror("mmap");
puts(buf);//打印共享内存的内容
munmap(buf,PAGE_SIZE);
close(fd);
return 0;
}