• mmap最简单的测试程序(用户空间与内核空间数据交换&&用户态和内核态的数据交换用例)


    //内核模块测试程序

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

    }

  • 相关阅读:
    14.5.5 Creating a File-Per-Table Tablespace Outside the Data Directory
    14.5.5 Creating a File-Per-Table Tablespace Outside the Data Directory
    php session 管理
    php session 管理
    CURD特性
    RabbitMQ学习总结(1)——基础概念详细介绍
    RabbitMQ学习总结(1)——基础概念详细介绍
    RabbitMQ学习总结(1)——基础概念详细介绍
    Java基础学习总结(39)——Log4j 1使用教程
    Java基础学习总结(39)——Log4j 1使用教程
  • 原文地址:https://www.cnblogs.com/shaoguangleo/p/2805882.html
Copyright © 2020-2023  润新知