2012年3月25日 Sunday
1、内核版本号2.6.33.20
2、kmalloc() kfree() vmalloc() vfree() __get_free_pages()的应用方法举例
3、模块源文件basicmem.c
- #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);
- 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_LICENSE("Dual BSD_GPL");
4、Makefile
- obj-m = basicmem.o
- CURRENT_PATH := $(shell pwd)
- LINUX_KERNEL := $(shell uname -r)
- LINUX_KERNEL_PATH := /usr/src/linux-$(LINUX_KERNEL)
- all:
- make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
- clean:
- #make -C $(LINUX_KERNEL_PAHT) M=$(CURRENT_PATH) clean
- rm *.mod.*
- rm *.order
- rm *.o
- rm *.symvers
5、运行方法
- ~/malloc# make
- ~/malloc# insmod memtest.ko
- ~/malloc# dmesg
6、运行结果
- [ 8913.072139] module memory test
- [ 8913.072162] kmalloc test
- [ 8913.072240] test memory
- [ 8913.072288] big memory ok
- [ 8913.072320] vmalloc test
- [ 8913.072416] vmalloc test ok
- [ 8913.072480] get_free_pages test
- [ 8913.072515] __get_free_pages test ok[5]
7、移除模块
- ~/mempool# rmmod memtest.ko
阅读(1045) | 评论(0) | 转发(0) |