mmap--最簡單的測試程序(用戶空間與內核空間數據交換&&用戶態和內核態的數據交換用例)

++++++ 轉載 ++++

//////////////////////////////////////////////////// Kernel mode module

#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);  // we will get value of 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("helloworld");
MODULE_DESCRIPTION("mmap test");

module_init(shao_init);
module_exit(shao_exit);


//////////////////////////////////////////////////// User mode applicaiton

#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;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章