简体   繁体   English

在 Linux 上调试信号处理程序

[英]Debugging signal handlers on Linux

I've set a signal handler for SIGCHLD.我已经为 SIGCHLD 设置了一个信号处理程序。 Out of curiosity, I'd like to try and debug the signal handler from within gdb.出于好奇,我想尝试从 gdb 中调试信号处理程序。 Is there any way I could do that?有什么办法可以做到吗?

I tried setting a breakpoint on the handler and running the binary from within gdb;我尝试在处理程序上设置断点并从 gdb 中运行二进制文件; however I dont seem to be able to debug the handler instruction by instruction.但是我似乎无法通过指令调试处理程序指令。 Is there any way I could go about doing that?有什么办法可以去做吗? I tried setting a hardware breakpoint but that did not help either.我尝试设置硬件断点,但这也无济于事。 The code I'm playing around with is shown below.我正在使用的代码如下所示。

I'm trying this on a 64 bit Ubuntu machine.我正在 64 位 Ubuntu 机器上尝试这个。

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int VAL = 0;
void handler(int sig) {
  VAL=1;
}

int main(int argc, const char *argv[]) {
  int pid, status;
  signal(SIGCHLD, handler);

  pid = fork();
  if ( pid == 0 ) exit(0);

  wait(&status);
  printf("Returned from handler %d\n", VAL);
  return 0;
}

The output printed is "Returned from handler 1" showing that SIGCHLD is handled by the process and not gdb;打印的输出是“Returned from handler 1”,表明 SIGCHLD 是由进程而不是 gdb 处理的; info signal from within gdb also suggests the same.来自 gdb 内的info signal也暗示了同样的情况。

GDB's handle command can be used.可以使用 GDB 的 handle 命令。 The handle command takes, as argument, a list of signals (to be handled) followed by actions. handle 命令将一系列信号(待处理)后跟动作作为参数。 also you can use following gdb options nostop & pass (let program see this signal).你也可以使用以下 gdb 选项 nostop & pass(让程序看到这个信号)。
http://sunsite.ualberta.ca/Documentation/Gnu/gdb-5.0/html_node/gdb_38.html http://sunsite.ualberta.ca/Documentation/Gnu/gdb-5.0/html_node/gdb_38.html

You are almost certainly compiling with optimizations turned on.您几乎可以肯定是在打开优化的情况下进行编译。 This, combined with the non-volatile VAL , give permission to your compiler to perform what seems like an aggressive optimization.这与非易失性VAL相结合,允许您的编译器执行看似激进的优化。

Turn optimizations off ( -O0 for GCC) or qualify VAL as volatile to have the desired effect.关闭优化( -O0用于 GCC)或将VAL限定为volatile以获得所需的效果。

If you are ok with using threads there is a way.如果您可以使用线程,那么有一种方法。 Create a thread and block it on a Condition Variable.创建一个线程并在条件变量上阻止它。 In the signal handler just signal the condition variable and the thread will break at the line you have put break on.在信号处理程序中,只需向条件变量发出信号,线程将在您设置中断的行处中断。 Unfortunately directly on signal i am not sure what will happen some signals are issues with gdb in my experience.不幸的是,直接在信号上我不确定会发生什么,根据我的经验,有些信号是 gdb 的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM