12

I have a faulty program that when execute receive a SIGSEGV.

I can use gdb like this:

$ gdb ./prog 

But I would prefer that gdb catch the SIGSEGV from prog and attach it automatically.

$ ./prog
Segmentation Fault
(gdb) ...

Is there a way to do that?

Thanks

mathk
  • 7,973
  • 6
  • 45
  • 74

3 Answers3

15

Hmm. You can set up a signal handler to launch the debugger with the current process. That way you can inspect the whole state "live".

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

const char *prog=0;
void fn(int signum)
{

    char buf[256]; 
    snprintf(buf,255,"ddd %s %d",prog,getpid());
    system(buf);
}
int main(int argc, char **argv)
{
    prog=argv[0];
    signal(SIGSEGV,&fn);
    int *p=0; 
    int k=*p;
}

UPDATE: Chaged according to the suggestions of miedwar and Fanatic23. Current Ubuntu distributions are configured to disallow debugging of non-child processes. See https://askubuntu.com/questions/41629/after-upgrade-gdb-wont-attach-to-process for a fix.

Community
  • 1
  • 1
Nordic Mainframe
  • 28,058
  • 10
  • 66
  • 83
4

Well you can always create a core file and then analyse the callstack using gdb on that core. You can check out the man page for ulimit to do so.

Check this link for more info.

Community
  • 1
  • 1
Praveen S
  • 10,355
  • 2
  • 43
  • 69
3

To add to Mainframe's answer you can link your app with libdebugme (or simply LD_PRELOAD it) to achieve similar functionality. For example:

DEBUGME_OPTIONS=handle_signals=1 LD_PRELOAD=libdebugme.so ./app
yugr
  • 19,769
  • 3
  • 51
  • 96