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

后端 未结 10 1155
悲&欢浪女
悲&欢浪女 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:00

    Invoke

    abort();
    

    Related, sometimes you'd like a back trace without an actual core dump, and allow the program to continue running: check out glibc backtrace() and backtrace_symbols() functions: http://www.gnu.org/s/libc/manual/html_node/Backtraces.html

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

    Sometimes it may be appropriate to do something like this:

    int st = 0;
    pid_t p = fork();
    
    if (!p) {
        signal(SIGABRT, SIG_DFL);
        abort(); // having the coredump of the exact copy of the calling thread
    } else {
        waitpid(p, &st, 0); // rip the zombie
    }
    
    // here the original process continues to live
    

    One problem with this simple approach is that only one thread will be coredumped.

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

    A few years ago, Google released the coredumper library.

    Overview

    The coredumper library can be compiled into applications to create core dumps of the running program -- without terminating. It supports both single- and multi-threaded core dumps, even if the kernel does not natively support multi-threaded core files.

    Coredumper is distributed under the terms of the BSD License.

    Example

    This is by no means a complete example; it simply gives you a feel for what the coredumper API looks like.

    #include <google/coredumper.h>
    ...
    WriteCoreDump('core.myprogram');
    /* Keep going, we generated a core file,
     * but we didn't crash.
     */
    

    It's not what you were asking for, but maybe it's even better :)

    0 讨论(0)
  • 2020-11-28 02:01
    #include <assert.h>
    .
    .
    .
         assert(!"this should not happen");
    
    0 讨论(0)
  • 2020-11-28 02:12
    #include <stdlib.h>   // C
    //#include <cstdlib>  // C++
    
    void core_dump(void)
    {
        abort();
    }
    
    0 讨论(0)
  • 2020-11-28 02:13

    Another way of generating a core dump:

    $ bash
    $ kill -s SIGSEGV $$
    

    Just create a new instance of the bash and kill it with specified signal. The $$ is the PID of the shell. Otherwise you are killing your current bash and will be logged out, terminal closed or disconnected.

    $ bash 
    $ kill -s SIGABRT $$
    $ bash
    $ kill -s SIGFPE $$
    
    0 讨论(0)
提交回复
热议问题