Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can gdb automatically attach a process on a SIGSEGV

Tags:

c

linux

gcc

gdb

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

like image 610
mathk Avatar asked Jul 13 '10 11:07

mathk


2 Answers

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
like image 106
yugr Avatar answered Oct 13 '22 00:10

yugr


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.

like image 41
Nordic Mainframe Avatar answered Oct 13 '22 01:10

Nordic Mainframe