代码之家  ›  专栏  ›  技术社区  ›  hhafez

如何以编程方式在C/C中导致核心转储++

  •  79
  • hhafez  · 技术社区  · 17 年前

    我知道我可以这样做:

    int * crash = NULL;
    *crash = 1;
    

    但我想知道是否有更干净的方法?

    10 回复  |  直到 9 年前
        1
  •  79
  •   Community Mohan Dere    9 年前

    提高6号信号( SIGABRT 在Linux中)是实现这一点的一种方法(但请记住,SIGABRT不是 必修的 在所有POSIX实现中都是6,因此您可能希望使用 西格布特 如果这不是quick'n'dirty调试代码,则返回值本身)。

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

    abort() 还会导致内核转储,您甚至可以这样做 通过调用来终止进程 fork() 然后 中止 仅限儿童-参见 this answer 详情请参阅。

        2
  •  77
  •   Community Mohan Dere    5 年前

    几年前,谷歌发布了 coredumper 图书馆

    概述

    Coredumper是根据BSD许可证的条款分发的。

    实例

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

    这不是你想要的,但也许更好:)

        3
  •  37
  •   ks1322    8 年前

    如清单所列 signal manpage

    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
    

    确保启用核心转储:

    ulimit -c unlimited
    
        4
  •  31
  •   Jonathan Leffler    17 年前
    #include <stdlib.h>   // C
    //#include <cstdlib>  // C++
    
    void core_dump(void)
    {
        abort();
    }
    
        5
  •  11
  •   Community Mohan Dere    6 年前

    援引

    abort();
    

    与此相关,有时您需要一个没有实际内核转储的回溯跟踪,并允许程序继续运行:检查glibc backtrace()和backtrace_symbols()函数: http://www.gnu.org/s/libc/manual/html_node/Backtraces.html

        6
  •  6
  •   Radim Köhler user2134822    12 年前

    生成核心转储的另一种方法:

    $ bash
    $ kill -s SIGSEGV $$
    

    只需创建一个新的bash实例,并使用指定的信号杀死它。这个 $$ 是的PID 贝壳。否则,您将终止当前bash,并将注销、关闭终端或断开连接。

    $ bash 
    $ kill -s SIGABRT $$
    $ bash
    $ kill -s SIGFPE $$
    
        7
  •  4
  •   Eugene Yokota    17 年前

    你可以用 kill(2) 发出信号。

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

    所以

    kill(getpid(), SIGSEGV);
    
        8
  •  2
  •   Brent Writes Code    6 年前

    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
    

        9
  •  1
  •   karthik339    12 年前
     #include <stdio.h>
     #include <stdlib.h>
     int main()
     {
       printf("\n");
       printf("Process is aborting\n");
       abort();
       printf("Control not reaching here\n");
       return 0;
     }
    

    无论您想在哪里使用此方法:)

        10
  •  0
  •   sigjuice    17 年前
    #include <assert.h>
    .
    .
    .
         assert(!"this should not happen");
    
    推荐文章