How to view thread stack with pstack tool

Author: Zhu Jincan
Source: clever101's column

  Pstack is a tool for viewing the stack of running threads under Linux. It is essentially a shell script. # 1. Installation of pstack tool Many times pstack and gdb are installed together. However, some Linux systems do not come with the pstack tool. It is also very simple to determine whether there is a pstack tool in the system, just run: pstack in the shell terminal, if not, it will prompt that the command cannot be found. If there is no pstack tool, you can create a new one in the system. The specific method is to create a shell script. The code is as follows:
#!/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:-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'

2. Use of pstack tool

  If the system is directly equipped with the pstack tool, the usage is pstack pid #pid is the process id
If the system does not have it, generate a pstack.sh from the above shell script, copy it to the /usr/bin directory, and then
pass chmod 777 /usr/bin/ pstack.sh #Grant permission to run pstack.sh, then
sudo pstack.sh pid #Run pstack.sh requires administrator permission

Guess you like

Origin blog.csdn.net/clever101/article/details/127189516