pstack是一个shell脚本,用于打印正在运行的进程的栈跟踪信息,它实际上是gstack的一个链接,而gstack本身是基于gdb封装的shell脚本.。此命令可显示每个进程的栈跟踪。pstack 命令必须由相应进程的属主或 root 运行。可以使用 pstack 来确定进程挂起的位置。此命令允许使用的唯一选项是要检查的进程的 PID。

    与jstack功相比, 它能对潜在的死锁予以提示, 而pstack只提供了线索, 需要gdb进一步的确定。

    pstack是gdb的一部分,如果系统没有pstack命令,使用yum搜索安装gdb即可。

    这个命令在排查进程问题时非常有用,比如我们发现一个服务一直处于work状态(如假死状态,好似死循环),使用这个命令就能轻松定位问题所在;可以在一段时间内,多执行几次pstack,若发现代码栈总是停在同一个位置,那个位置就需要重点关注,很可能就是出问题的地方;

    运行格式为:pstack

    pstack是什么?
    pstack 其实就是封装gdb的一个shell脚本。
    打印堆栈其实就是 gdb 的 bt 命令。**

    1. [root@host-172-24-115-217 ~]# ll /usr/bin/pstack
    2. lrwxrwxrwx. 1 root root 6 Apr 26 12:54 /usr/bin/pstack -> gstack
    3. [root@host-172-24-115-217 ~]# file /usr/bin/gstack
    4. /usr/bin/gstack: POSIX shell script text executable
    5. [root@host-172-24-115-217 ~]# cat /usr/bin/gstack
    6. #!/bin/sh
    7. if test $# -ne 1; then
    8. echo "Usage: `basename $0 .sh` " 1>&2
    9. exit 1
    10. fi
    11. if test ! -r /proc/$1; then
    12. echo "Process $1 not found." 1>&2
    13. exit 1
    14. fi
    15. # GDB doesn't allow "thread apply all bt" when the process isn't
    16. # threaded; need to peek at the process to determine if that or the
    17. # simpler "bt" should be used.
    18. backtrace="bt"
    19. if test -d /proc/$1/task ; then
    20. # Newer kernel; has a task/ directory.
    21. if test `/bin/ls /proc/$1/task | /usr/bin/wc -l` -gt 1 2>/dev/null ; then
    22. backtrace="thread apply all bt"
    23. fi
    24. elif test -f /proc/$1/maps ; then
    25. # Older kernel; go by it loading libpthread.
    26. if /bin/grep -e libpthread /proc/$1/maps > /dev/null 2>&1 ; then
    27. backtrace="thread apply all bt"
    28. fi
    29. fi
    30. GDB=${GDB:-/usr/bin/gdb}
    31. if $GDB -nx --quiet --batch --readnever > /dev/null 2>&1; then
    32. readnever=--readnever
    33. else
    34. readnever=
    35. fi
    36. # Run GDB, strip out unwanted noise.
    37. $GDB --quiet $readnever -nx /proc/$1/exe $1 <&1 |
    38. set width 0
    39. set height 0
    40. set pagination no
    41. $backtrace
    42. EOF
    43. /bin/sed -n \
    44. -e 's/^\((gdb) \)*//' \
    45. -e '/^#/p' \
    46. -e '/^Thread/p'