Calling debugger from program C

I am reading David Hanson's book Interfaces and Implementations. This question of exercises seems interesting and cannot find a solution:

On some systems, a program may call the debugger on its own when it detects an error. This tool is especially useful during times when approval errors can be common.

Can you give a brief example of how to call the debugger.

void handle_seg_fault(int arg)
{
    /* how to invoke debugger from within here */
}

int main()
{
    int *ptr = NULL;
    signal(SIGSEGV, handle_seg_fault);
    /* generate segmentation fault */
    *ptr = 1;
}
+5
source share
2 answers

When developing a Christian.K comment, a fork()debugger in the face of something like SIGFPE or SIGSEGV might not be the best of ideas, because ...

  • Your program is potentially corrupt to begin with, making it fork()unsafe;
  • - , , ;
  • , ;
  • , , coredump .

coredump, , . .

+4

:

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

void exception_handler(int)
{
    int pid = getpid();
    if (fork() != 0) {
        while(true) sleep(1000);
    }
    char buf[20];
    sprintf(buf, "--pid=%u", pid);
    execlp("gdb", "gdb", buf, NULL);
    exit(-1);
}

int init()
{
    if (signal(SIGSEGV, exception_handler) < 0) {
       return errno;
    }
    if (signal(SIGILL, exception_handler) < 0) {
        return errno;
    }
    if (signal(SIGFPE, exception_handler) < 0) {
        return errno;
    }
    return 0;
}

int main()
{
    if (int rc = init()) {
       fprintf(stderr, "init error: %s\n", strerror(rc));
       return 1;
    }
    *((char*)(0)) = 1;
}
+3

All Articles