2

I've set a signal handler for SIGCHLD. Out of curiosity, I'd like to try and debug the signal handler from within gdb. Is there any way I could do that?

I tried setting a breakpoint on the handler and running the binary from within 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.

#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; info signal from within gdb also suggests the same.

  • It won't harm if you add `volatile` to the VAL variable. (and please don't use CAPS-only identifiers) – joop Mar 24 '14 at 10:57

3 Answers3

1

GDB’s handle command can be used. The handle command takes, as argument, a list of signals (to be handled) followed by actions. also you can use following gdb options nostop & pass (let program see this signal).
http://sunsite.ualberta.ca/Documentation/Gnu/gdb-5.0/html_node/gdb_38.html

nikhil mehta
  • 972
  • 15
  • 30
1

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.

Turn optimizations off (-O0 for GCC) or qualify VAL as volatile to have the desired effect.

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
0

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.

Adnan Akbar
  • 718
  • 6
  • 16