用于捕获 SIGSEGV 的 gdb 脚本

问题描述 投票:0回答:1

我尝试使用 gdb 调试 C 程序(不是在交互模式下)。在程序中,我使用signal来检查分段错误,但我使用gdb来查找代码的位置。

如果我使用

gdb -ex "handle SIGSEGV stop print pass" ./script -ex "run"

它捕获了 gdb 和程序中的错误,但我需要输入

continue
来调试其余代码。

如果我使用

gdb -ex "handle SIGSEGV nostop print pass" ./script -ex "run"

gdb 仅打印

Thread 86241 "server-ev" received signal SIGSEGV, Segmentation fault.
,而不打印导致错误的代码行。

我还尝试了配置文件

define handle_sigsegv
    bt
    continue
end

但运气不佳。

如何编写 gdb 脚本(无需交互)来打印 SIGSEGV(包括错误行)并继续?

c gdb
1个回答
0
投票

假设您的代码如下所示:

#include <signal.h>
#include <stdio.h>

void handler(int signo)
{
  fprintf(stderr, "Caught signal %d\n", signo);
  signal(signo, SIG_DFL);
  raise(signo);
}

int crash()
{
  int *p = (int*)42;
  return p[0];
}

int main()
{
  signal(SIGSEGV, handler);
  return crash();
}
gcc -g t.c && ./a.out
Caught signal 11
Segmentation fault

使用

gdb -q -batch -ex run -ex continue ./a.out

Program received signal SIGSEGV, Segmentation fault.
0x00005555555551b1 in crash () at t.c:14
14        return p[0];
Caught signal 11

Program received signal SIGSEGV, Segmentation fault.
0x00005555555551b1 in crash () at t.c:14
14        return p[0];
© www.soinside.com 2019 - 2024. All rights reserved.