Linux内存管理实践-打印内存区域

13 11 月, 2010 by edsionte Leave a reply »

本文将通过一些简单的内核模块程序,显示一个进程的所有内存区域。通过此程序理解进程的整个地址空间与内存区域之间的关系。

打印内存区域

上文中,我们通过打印某个进程的maps文件来查看某个进程的内存区域。如果你理解了进程,进程的用户空间,内存区域三者之间的关系,那么就可以通过内核模块的方式打印指定进程的内存区域。

通过在内核模块加载函数中调用下述函数,来打印当前进程的内存区域。首先通过全局变量current获得当前进程的mm字段,该字段指向当前进程的用户空间(mm_struct);由于多个内存区域(vm_area_struct)是通过一个双链表(最新内核中)链接在一起的,所以在接下来的for循环当中,依次遍历各个内存区域,打印当前内存区域的起始地址和终止地址,并且打印内核对该区域的操作权限。完整代码在这里

01static void list_myvma(void)
02{
03    struct mm_struct *mm = current->mm;
04    struct vm_area_struct *vma;
05 
06    printk("list vma..\n");
07        //print the current process's name and pid
08    printk("current:%s pid:%d\n",current->comm,current->pid);
09 
10    down_read(&mm->mmap_sem);
11    //vma is a linklist
12    for(vma = mm->mmap; vma; vma = vma->vm_next)
13    {
14        //from the begining to the ending of a virtual memory area
15        printk("0x%lx-0x%lx ",vma->vm_start,vma->vm_end);
16        //check the flags of this VMA
17        if(vma->vm_flags & VM_READ)
18            printk("r");
19        else
20            printk("-");
21 
22        if(vma->vm_flags & VM_WRITE)
23            printk("w");
24        else
25            printk("-");
26 
27        if(vma->vm_flags & VM_EXEC)
28            printk("x");
29        else
30            printk("-");
31 
32        if(vma->vm_flags & VM_SHARED)
33            printk("s");
34        else
35            printk("p");
36 
37            printk("\n");
38 
39    }
40    up_read(&mm->mmap_sem);
41}

试一下吧!

Advertisement

5 comments

  1. ltang说道:

    源代码在http://www.kerneltravel.net/?p=450;
    但是编译时报错:
    error:dereferencing pointer to incomplete type
    你有源文件么?

    [回复一下]

    edsionte 回复:

    @ltang, 请问您是对代码有疑惑还是要源码的?源码我这里是没有的,不好意思。

    [回复一下]

    tony 回复:

    @edsionte, 我是在ubuntu9.10上面编译,内核版本为2.6.31.4,用上面网页上的链接
    处的源码,编译报错.问题原因也找到:缺少两个头文件:
    #include
    #include

    [回复一下]

    edsionte 回复:

    @ltang, 好的。这个例子挺好的~

    [回复一下]

  2. lwp说道:

    学习了!

    [回复一下]

发表回复

windows 7 ultimate product key

windows 7 ultimate product key

winrar download free

winrar download free

winzip registration code

winzip registration code

winzip free download

winzip free download

winzip activation code

winzip activation code

windows 7 key generator

windows 7 key generator

winzip freeware

winzip freeware

winzip free download full version

winzip free download full version

free winrar download

free winrar download

free winrar

free winrar

windows 7 crack

windows 7 crack

windows xp product key

windows xp product key

windows 7 activation crack

windows7 activation crack

free winzip

free winzip

winrar free download

winrar free download

winrar free

winrar free

download winrar free

download winrar free

windows 7 product key

windows 7 product key