主要使用了getcontext和walkcontext两个函数。
- #include stdio.h>
-
#include stdlib.h>
-
#include unistd.h>
-
#include ucontext.h>
-
#include dlfcn.h>
-
-
int walker(uintptr_t pc, int sig, void *usrarg) {
-
-
Dl_info dlip;
-
-
if(dladdr((void *)pc, &dlip)) {
-
(void)printf(" %08lx %s %s\n", pc, dlip.dli_fname, dlip.dli_sname);
-
return 0;
-
} else {
-
perror("dladdr()");
-
return -1;
-
}
-
-
}
-
-
int bar() {
-
-
char buf[64];
-
snprintf(buf, 64, "/bin/pstack %i", getpid());
-
system(buf);
-
-
(void)printf("\nprintstack()\n");
-
printstack(0);
-
-
ucontext_t ucp;
-
if(getcontext(&ucp)) {
-
perror("\ngetcontext()");
-
return -1;
-
} else {
-
(void)printf("\nwalkcontext()\n");
-
return walkcontext(&ucp, &walker, NULL);
-
}
-
-
}
-
-
int main(int argc, char *argv[]) {
-
return bar();
- }
执行结果:
$ gcc -g -o bar bar.c
$ ./bar
(pstack的输出)
ff2cd4d8 waitid (0, 4067, ffbff4b8, 3)
ffbff664, ff390140) ff2bce94 waitpid (4067, ffbff60c, 0, 0, + 60
000, 1, ff3303d8, ff ff2afe20 system (ffbff928, ff339bd0, 20bff664) + 2ec
4, ff392a00, ff2b6d 000108b8 bar (20c70, 1c00, ff335900,6c) + 38
20c94, ff3900c0, 0) 00010968 main (1, ffbffa4c, ffbffa54, + c
00010698 _start (0, 0, 0, 0, 0, 0) + 5c
printstack()
/tmp/bar:bar+0x54
/tmp/bar:main+0xc
/tmp/bar:_start+0x5c
walkcontext()
00010968 /tmp/bar main
00010698 /tmp/bar _start
相关链接: