gpt4 book ai didi

c++ - 有时无法从/proc/self/maps 获取堆栈范围

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:20:37 24 4
gpt4 key购买 nike

我有一个问题。我正在尝试从/proc/self/maps 伪文件获取堆栈偏移范围。但我有时会有奇怪的事情。这是我的代码

 fp = fopen("/proc/self/maps", "r");
if (fp == NULL) {
perror("Error opening file");
return NULL;
}
while (fgets(line, 2048, fp) != NULL) {
if (strstr(line, "stack") != NULL) {
printf("%s", line);
}
}

如果你用一个或多个线程启动程序,你可以查看这个伪文件并得到类似这样的东西

7f20423a6000-7f2042ba6000 rw-p 00000000 00:00 0                          [stack:3936]
7fffbe95e000-7fffbe97f000 rw-p 00000000 00:00 0 [stack]

这里第一行是线程栈,第二行是进程栈。但问题是有时我无法获得线程堆栈。它可能是第一次出现,也可能出现在下一次执行中,因此不确定。在某些发行版中,它根本不显示线程堆栈,我认为问题不在于发行版中伪文件的不同实现,而在于其他方面。请帮忙解决这个问题

编辑

我其实是在thread内部调用了这个函数,所以我通过pthread_create(&tid, NULL, proc_stack, NULL);创建thread,我也一直在思考这个问题。也许在线程启动后需要一些时间来更新这个伪文件,这只是我在这里看到的原因之一。

EDIT2

我试过强制调用 sleep ,但这没有帮助,但最奇怪的是,在一个发行版上它显示线程堆栈,而在另一个发行版上却没有。

最佳答案

在我的系统上你的程序也没有显示第二个 stack 段,但似乎在 [heap] 上面分配了 5 个段,其中一个用于线程stack(proc_stack()的局部变量存放在该段)。

我用来检查它的代码 (test.c):

#include <stdio.h>
#include <string.h>
#include <pthread.h>

void* proc_stack(void* p){
FILE *fp;
char line[2048];
fp = fopen("/proc/self/maps", "r");
if (fp == NULL) {
perror("Error opening file");
return NULL;
}
while (fgets(line, 2048, fp) != NULL) {
// if (strstr(line, "stack") != NULL) {
printf("%s", line);
// }
}
printf("addr = %p %p\n", &fp, &line);
return NULL;
}

int main(){
pthread_t tid;
void *rv;
proc_stack( NULL );
puts("main");
pthread_create( &tid, NULL, proc_stack, NULL );
pthread_join( tid, &rv );
return 0;
}

使用 gcc -Wall test.c -pthread 编译。结果(删除了一些行):

...
01933000-01954000 rw-p 00000000 00:00 0 [heap]
...
7fff75be3000-7fff75c04000 rw-p 00000000 00:00 0 [stack]
7fff75d97000-7fff75d98000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
addr = 0x7fff75c00e68 0x7fff75c00e70
main
...
01933000-01954000 rw-p 00000000 00:00 0 [heap]
7f3be0000000-7f3be0021000 rw-p 00000000 00:00 0
7f3be0021000-7f3be4000000 ---p 00000000 00:00 0
7f3be6b79000-7f3be6b7a000 rw-p 00000000 00:00 0
7f3be6b7a000-7f3be6b7b000 ---p 00000000 00:00 0
7f3be6b7b000-7f3be737b000 rw-p 00000000 00:00 0
...
7fff75be3000-7fff75c04000 rw-p 00000000 00:00 0 [stack]
7fff75d97000-7fff75d98000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
addr = 0x7f3be73796c8 0x7f3be73796d0

关于c++ - 有时无法从/proc/self/maps 获取堆栈范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26913654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com