为什么proc / self / maps没有正确显示映射

时间:2012-01-14 18:30:16

标签: c linux gcc x86-64

当我运行以下代码时,

int x[4096];
int *y;
int *m;

void main()
{
    y = (int*)malloc( 4096 * sizeof(int) );
    m = (int*)mmap( 0, 4096 * sizeof(int), PROT_READ | PROT_WRITE, 
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 );

    printf( "x = %p, y = %p, m = %p\n\n", x, y, m );

    system( "cat /proc/self/maps" );
}

我得到以下输出,

x = 0x601060, y = 0x606010, m = 0x7ffff7ff5000

00400000-0040b000 r-xp 00000000 08:01 655382                             /bin/cat
0060a000-0060b000 r--p 0000a000 08:01 655382                             /bin/cat
0060b000-0060c000 rw-p 0000b000 08:01 655382                             /bin/cat
0060c000-0062d000 rw-p 00000000 00:00 0                                  [heap]
7ffff77b5000-7ffff7a59000 r--p 00000000 08:01 395618                     /usr/lib/locale/locale-archive
7ffff7a59000-7ffff7bd3000 r-xp 00000000 08:01 1062643                    /lib/libc-2.12.1.so
7ffff7bd3000-7ffff7dd2000 ---p 0017a000 08:01 1062643                    /lib/libc-2.12.1.so
7ffff7dd2000-7ffff7dd6000 r--p 00179000 08:01 1062643                    /lib/libc-2.12.1.so
7ffff7dd6000-7ffff7dd7000 rw-p 0017d000 08:01 1062643                    /lib/libc-2.12.1.so
7ffff7dd7000-7ffff7ddc000 rw-p 00000000 00:00 0 
7ffff7ddc000-7ffff7dfc000 r-xp 00000000 08:01 1062651                    /lib/ld-2.12.1.so
7ffff7fd9000-7ffff7fdc000 rw-p 00000000 00:00 0 
7ffff7ff9000-7ffff7ffb000 rw-p 00000000 00:00 0 
7ffff7ffb000-7ffff7ffc000 r-xp 00000000 00:00 0                          [vdso]
7ffff7ffc000-7ffff7ffd000 r--p 00020000 08:01 1062651                    /lib/ld-2.12.1.so
7ffff7ffd000-7ffff7ffe000 rw-p 00021000 08:01 1062651                    /lib/ld-2.12.1.so
7ffff7ffe000-7ffff7fff000 rw-p 00000000 00:00 0 
7ffffffde000-7ffffffff000 rw-p 00000000 00:00 0                          [stack]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]

现在,我的问题是,为什么分配为malloc,mmap或全局数据的内存不在 / proc / self / maps 所示的任何映射范围内?

1 个答案:

答案 0 :(得分:12)

当您运行system( "cat /proc/self/maps" );时,您会显示cat进程的映射。您可以在输出的第一行看到它是映射的cat可执行文件:

00400000-0040b000 r-xp 00000000 08:01 655382                             /bin/cat

您需要执行snprintf(..., "cat /proc/%d/maps", getpid());,或打开/ proc / self / pid文件并在自己的过程中自行阅读。