How to programmatically cause a core dump in C/C++

后端 未结 10 1156
悲&欢浪女
悲&欢浪女 2020-11-28 01:24

I would like to force a core dump at a specific location in my C++ application.

I know I can do it by doing something like:

int * crash = NULL;
*cras         


        
相关标签:
10条回答
  • 2020-11-28 02:16
     #include <stdio.h>
     #include <stdlib.h>
     int main()
     {
       printf("\n");
       printf("Process is aborting\n");
       abort();
       printf("Control not reaching here\n");
       return 0;
     }
    

    use this approach wherever you want :)

    0 讨论(0)
  • 2020-11-28 02:18

    You can use kill(2) to send signal.

    #include <sys/types.h>
    #include <signal.h>
    int kill(pid_t pid, int sig);
    

    So,

    kill(getpid(), SIGSEGV);
    
    0 讨论(0)
  • 2020-11-28 02:25

    As listed in the signal manpage, any signal with the action listed as 'core' will force a core dump. Some examples are:

    SIGQUIT       3       Core    Quit from keyboard
    SIGILL        4       Core    Illegal Instruction
    SIGABRT       6       Core    Abort signal from abort(3)
    SIGFPE        8       Core    Floating point exception
    SIGSEGV      11       Core    Invalid memory reference
    

    Make sure that you enable core dumps:

    ulimit -c unlimited
    
    0 讨论(0)
  • 2020-11-28 02:26

    Raising of signal number 6 (SIGABRT in Linux) is one way to do it (though keep in mind that SIGABRT is not required to be 6 in all POSIX implementations so you may want to use the SIGABRT value itself if this is anything other than quick'n'dirty debug code).

    #include <signal.h>
    : : :
    raise (SIGABRT);
    

    Calling abort() will also cause a core dump, and you can even do this without terminating your process by calling fork() followed by abort() in the child only - see this answer for details.

    0 讨论(0)
提交回复
热议问题