pstack是Linux下一款堆栈跟踪工具,可以打印一个在跑程序的实时堆栈信息,其用法非常简单,只需要给定进程号即可:
Usage: pstack <process-id>
举例如下:
[regli@centos ~]$ pstack 23741
#0 0x00007f212faa2480 in __nanosleep_nocancel () from /lib64/libc.so.6
#1 0x00007f212faa2334 in sleep () from /lib64/libc.so.6
#2 0x0000000000400a8b in main ()
pstack其实是个Shell脚本,核心原理是GDB的thread apply all bt命令,基本逻辑是通过进程号process-id来分析是否使用了多线程,同时使用GDB Attach到在跑进程上,最后调用bt子命令后简单格式化输出,代码如下:
[regli@centos ~]$ which pstack
/usr/bin/pstack
[regli@centos ~]$ cat /usr/bin/pstack
#!/bin/sh
if test $# -ne 1; then
echo "Usage: `basename $0 .sh` <process-id>" 1>&2
exit 1
fi
if test ! -r /proc/$1; then
echo "Process $1 not found." 1>&2
exit 1
fi
# GDB doesn't allow "thread apply all bt" when the process isn't
# threaded; need to peek at the process to determine if that or the
# simpler "bt" should be used.
backtrace="bt"
if test -d /proc/$1/task ; then
# Newer kernel; has a task/ directory.
if test `/bin/ls /proc/$1/task | /usr/bin/wc -l` -gt 1 2>/dev/null ; then
backtrace="thread apply all bt"
fi
elif test -f /proc/$1/maps ; then
# Older kernel; go by it loading libpthread.
if /bin/grep -e libpthread /proc/$1/maps > /dev/null 2>&1 ; then
backtrace="thread apply all bt"
fi
fi
GDB=${GDB:-/usr/bin/gdb}
# Run GDB, strip out unwanted noise.
# --readnever is no longer used since .gdb_index is now in use.
$GDB --quiet -nx $GDBARGS /proc/$1/exe $1 <<EOF 2>&1 |
set width 0
set height 0
set pagination no
$backtrace
EOF
/bin/sed -n \
-e 's/^\((gdb) \)*//' \
-e '/^#/p' \
-e '/^Thread/p'
Here Document也是一种IO重定向,IO结束时会发EOF给GDB。
GDB的东西内容非常多,这里不展开,pstack里最核心的就是调用GDB,attach到对应进程,然后执行bt命令,如果程序是多线程就执行thread apply all bt命令,最后quit退出。
附带GDB文档的两个说明,第一个是关于attach的:
The first thing GDB does after arranging to debug the specified process is to stop it.
看了这个应该就很容易明白为什么不能随便在生产环境中去attach一个正在运行的程序,如果attach上以后待着不动,程序就暂停了。
那为什么用pstack没啥事儿呢,原因是pstack执行了一个GDB的bt子命令后立即退出了,可是源代码里面没有执行quit,它是怎么退出的呢,看这个文档说明:
To exit GDB, use the quit command (abbreviated q), or type an end-of-file character (usually Ctrl-d).
Here Document IO重定向结束的标志是EOF,GDB读到了EOF自动退出了。
pstack里面检查进程是否支持多线程的方法是检查进程对应的proc目录,方法没什么可说的,其中Older kernel下是通过检查/proc/pid/maps是否加载libpthread来搞的,这种是动态的,类似于静态的ldd。这种方法其实不太严谨,但由于GDB的thread apply all bt对多线程的支持也不是特别完美,所以也无可厚非。这里简单说说Linux的procfs。
虽然并不是所有的UNIX-Like操作系统都支持procfs,也不是Linux首创了这种虚拟文件系统,但绝对是Linux将其发扬光大的,早起内核中甚至达到了滥用的程度,内核开发者喊了好多年,说procfs即将被淘汰,但依然很火,主要是因为太方便了,比如procfs可以很容易的进行应用层与内核态进行通信。
procfs在Linux中的应用不止是进程信息导出,详细的应用与内核模块联动,后续会写专门的文章介绍,如有兴趣,可以参考《深入理解Linux内核架构》和《Linux设备驱动程序》,关于进程的,以下信息可以了解一下:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。