曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4355|回复: 0
打印 上一主题 下一主题

动态内存使用实例

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2009-9-1 02:11:36 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
代码
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>

void kmalloc_test (void)
{
    char *buff;

    printk ("kmalloc test\n");
   
    buff = kmalloc (1024, GFP_KERNEL);
    if (buff != NULL) {
        sprintf (buff, "test memory\n");
        printk (buff);

        kfree (buff);
    }

    buff = kmalloc (32 * PAGE_SIZE, GFP_KERNEL);
    if (buff != NULL) {
        printk ("Big Memory OK\n");
        kfree (buff);
    }
}

void vmalloc_test (void)
{
    char *buff;
   
    printk ("vmalloc test\n");

    buff = vmalloc (33 * PAGE_SIZE);
    if (buff != NULL) {
        sprintf (buff, "vmalloc test ok\n");
        printk (buff);
       
        vfree (buff);
    }
}

void get_free_pages_test (void)
{
    char *buff;
    int order;

  
    printk ("get_free_pages test\n");

    order = get_order (8192 * 10);
    printk ("%d\n", PAGE_SHIFT);

    buff = __get_free_pages (GFP_KERNEL, order);
    if (buff != NULL) {
        sprintf (buff, "__get_free_pages test ok [%d]\n", order);
        printk (buff);

        free_pages (buff, order);
    }
}

int memtest_init (void)
{

    printk ("Module Memory Test\n");
   
    kmalloc_test ();
    vmalloc_test ();
    get_free_pages_test ();

    return 0;
}

void memtest_exit (void)
{
    printk ("Module Memory Test End\n");
}

module_init (memtest_init);
module_exit (memtest_exit);
输出
Module Memory Test
kmalloc test
test memory
Big Memory OK
vmalloc test
vmalloc test ok
get_free_pages test
12
__get_free_pages test ok [5]
在用 rmmod 命令注销掉模块后,在 memtest_exit 中的打印信息(Module Memory Test End)才会输出来。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-4 01:59 , Processed in 0.076886 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表