在不附加GDB的情况下获取所有线程的堆栈跟踪

时间:2012-09-12 19:24:49

标签: c++ linux gdb

有没有办法在不附加GDB的情况下打印所有线程的堆栈跟踪?

或者是否有一个命令可以用作gdb批处理模式来打印所有线程的堆栈跟踪?

6 个答案:

答案 0 :(得分:12)

GDB中有一个thread apply all命令:

(gdb) thread apply all bt
Thread 12 (Thread 0x7f7fe2116700 (LWP 5466)):
#0  sem_wait () at ../nptl/sysdeps/unix/sysv/linux/x86_64/sem_wait.S:86
#1  0x0000000000425358 in ?? ()
...
Thread 1 (Thread 0x7f7feabc27c0 (LWP 5465)):
#0  0x00007f7fe76c5203 in select () at ../sysdeps/unix/syscall-template.S:82

可悲的是,GDB似乎无法从管道中读取命令,因此要以批处理模式运行命令,必须使用临时文件:

$ gdbbt() {
  tmp=$(tempfile)
  echo thread apply all bt >"$tmp"
  gdb -batch -nx -q -x "$tmp" -p "$1"
  rm -f "$tmp"
}
$ gdbbt $(pidof $SHELL)

答案 1 :(得分:3)

的pstack?

用法:

pstack <pid>

从手册页:

pstack - print a stack trace of a running process
...
If the process is part of a thread group, then pstack will print out a stack trace for each of the threads in the group.

答案 2 :(得分:3)

其他实用程序中的

elfutils包括<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> </html>

eu-stack

它比gdb或pstack更快,它只是围绕gdb的shell脚本包装器。要打印堆栈跟踪运行eu-stack Print a stack for each thread in a process or core file. ,如下所示:

eu-stack

答案 3 :(得分:1)

我一直在使用它:

pidof program | xargs -n1 sudo gdb --batch -ex "thread apply all bt" -p

答案 4 :(得分:1)

以下脚本适用于linux 请注意,它首先找到可执行文件的目录并更改到该目录(因为可执行文件可以通过在链接期间使用-Wl,-rpath,$ dir来使用具有相对路径的共享库,并且您希望gdb找到符号用于堆栈跟踪的这些共享库)。 它还假定系统上存在gdb。

#!/bin/bash

pid=$1

EXE=`readlink -f /proc/$pid/exe`

DIR=`dirname $EXE`

cd $DIR

gdb $EXE --batch -ex "attach $pid" -ex "thread apply all bt"

答案 5 :(得分:0)

在linux中所有线程本质上都是轻量级进程,它们获得单独的LWP PID。您可以使用基于pstop的脚本或echo w /proc/sysrq-trigger来转储这些状态。这将为您提供I/O中线程的/var/log/messages状态。

虽然这不会给你完整的堆栈跟踪。但它是定期调试线程状态的好方法。

您还可以通过查看/proc/sched_debug来查看当前的调度程序状态,以查看正在调度的任务等等。