How to debug signal handlers using GDB

At times, one might want to debug a signal handler using GDB. Looks simple, just set a breakpoint at the entry! But there is tiny glitch. Consider the following program.

/*
  @file : sig.c
*/

#include
#include

void signalhandler(int signum) {
  printf("\n SIGINT caught : %d", signum);
}

int main() {
  signal(SIGINT, (void*)signalhandler);

  while (1) {
    printf("\n looping : inside main()");
    sleep(1);
  }
}

Now, lets try to debug the signal handler function using GDB.

# Set a breakpoint in the signal handler function.
(gdb) b signalhandler 
Breakpoint 1 at 0x40058f: file sig.c, line 5.
(gdb) r
Starting program: /home/nirbhay/project/sandbox/c/signal/a.out 

 looping : inside main()
 looping : inside main()
 looping : inside main()
 looping : inside main()
 looping : inside main()
# And now, Ctrl-C
^C
Program received signal SIGINT, Interrupt.
0x00007ffff7af5120 in __nanosleep_nocancel () at ../sysdeps/unix/syscall-template.S:82
82	../sysdeps/unix/syscall-template.S: No such file or directory.
	in ../sysdeps/unix/syscall-template.S
(gdb)

Its apparent that the signal that we are trying to send to the program is being intercepted by GDB and hence control never enters the signal handler (where we have already set a breakpoint).

In such scenarios, GDB’s handle command can be used. With this command we can alter the default behaviour of GDB towards signals. The handle command takes, as argument, a list of signals (to be handled) followed by actions. Of all the actions, ones that are of interest to us are : nostop (do not re-enter debugger if this signal happens) & pass (let program see this signal).

Lets now watch ’em in action :

(gdb) handle SIGINT nostop pass
SIGINT is used by the debugger.
Are you sure you want to change it? (y or n) y

Signal        Stop	Print	Pass to program	Description
SIGINT        No	Yes	Yes		Interrupt
(gdb) r
Starting program: /home/nirbhay/project/sandbox/c/signal/a.out 

 looping : inside main()
 looping : inside main()
^C
Program received signal SIGINT, Interrupt.

Breakpoint 1, signalhandler (signum=2) at sig.c:5
5	  printf("\n SIGINT caught : %d", signum);
(gdb)

Figlet : A cool tool

I recently came across ‘figlet‘. Its a handy tool to generate generate text in different styles & sizes that can be used in mail signatures, text documents, etc.

On ubuntu, ‘figlet’ package also comes with some other related tools like figlist (lists figlet fonts & control files), showfigfonts (prints a list of available figlet fonts).

Enjoy!