用户态和内核共享内存:最简单的例子
#include#include
#include
#include
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Wheelz");
MODULE_DESCRIPTION("mmap demo");
static unsigned long p = 0;
static int __init 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 fini(void)
{
ClearPageReserved(virt_to_page(p));
free_pages(p, 0);
}
module_init(init);
module_exit(fini);
用户态程序---------------------------------
#include
#include
#include
#include
#include
#define PAGE_SIZE (4*1024)
#define PAGE_OFFSET 0xc0000000
#define KERNEL_VIRT_ADDR 0xc5e3c000
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;
}