Linux下pstack的实现

Erlang非业余研究 2011-01-06 22:38:48 累计浏览 2,460 次

Linux下有时候我们需要知道一个进程在做什么,比如说程序不正常的时候,他到底在干吗?最直接的方法就是打印出他所有线程的调用栈,这样我们从栈再配合程序代码就知道程序在干吗了。
Linux下这个工具叫做pstack. 使用方法是

# pstack
Usage: pstack <process-id>

当然这个被调查的程序需要有符号信息。 比较雷人的是 这个程序竟然是个shell脚本,核心实现是gdb的 thread apply all bt, 我们可以观摩下他的实现,这个我们做类似的程序提供了一个很好的思路:

[root@=i ~]# cat `which 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}

if $GDB -nx --quiet --batch --readnever > /dev/null 2>&1; then
    readnever=--readnever
else
    readnever=
fi

# Run GDB, strip out unwanted noise.
$GDB --quiet $readnever -nx /proc/$1/exe $1 <<EOF 2>&1 |
$backtrace
EOF
/bin/sed -n \
    -e 's/^(gdb) //' \
    -e '/^#/p' \
    -e '/^Thread/p'

祝大家玩的开心。

同分类推荐文章

  1. NGINX Gateway Fabric 2.8: IP allow and deny lists, passive health checks, and cookie-based session persistence (2026-11-14 01:10:02)
  2. NGINX Ingress Controller 5.7: HTTP/2 to your upstreams, Opaque Secrets, and cert-manager challenges behind HTTPS redirects (2026-11-14 00:10:02)
  3. Hexo 文章一键发布到微信公众号 (2026-11-13 19:10:02)

查看更多 DevOps 文章 →

建议继续学习

  1. Fix Bug的五个阶段 (累计阅读 43,265)
  2. Bash的模式和配置文件加载 (累计阅读 24,812)
  3. 28个Unix/Linux的命令行神器 (累计阅读 17,183)
  4. Linux如何统计进程的CPU利用率 (累计阅读 16,953)
  5. 调试工具之GDB (累计阅读 15,173)
  6. 我的 RHCA 之路 (累计阅读 14,368)
  7. 我常用的主机监控shell脚本 (累计阅读 14,008)
  8. Linux内存点滴 用户进程内存空间 (累计阅读 13,956)
  9. 给程序员新手的一些建议 (累计阅读 13,518)
  10. Linux 性能监控、测试、优化工具 (累计阅读 13,460)