翻译:How to programmatically cause a core dump in C/C++

Stack overflow地址:How to programmatically cause a core dump in C/C++ - Stack Overflow


翻译:

我想要在我的C++程序中指定位置强制进行core dump操作。

我知道我可以像这么做:

int * crash = NULL;

*crash = 1;

但是我想知道还有更简洁的方法吗?

顺便说一下我使用Linux。


Answers1:

触发信号6(SIGABRT在Linux中)是一种方式来做这个(不过请记住SIGABRT并不强制为6在所有的POSIX实现中,因此你可能需要使用SIGABRT值本身可以在任何地方进行快速的调试代码)

#include

: : :

raise (SIGABRT);

调用abort()也会引起core dump,甚至你可以不中断你的程序通过调用fork(),然后在子进程中调用abort(),看this answer找到更多的细节。


Answers2:

几年前,google发布了coredumper库:

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

...

WriteCoreDump('core.myprogram');

/* Keep going, we generated a core file,

* but we didn't crash.

*/

这不是你想要的,但是可能是更好的。


Answer3:

在signal manpage所列的信号中,任何行为列带有"core"的信号都会强制产生core dump。一些例子如下:

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

确保你开启了core dumps:

ulimit -c unlimited


Answer4:

#include // C

//#include   // C++

void core_dump(void)

{

    abort();

}


Answer5:

abort();

顺便说下,你可能想要进行跟踪在没有core dump的情况下,并且允许程序继续运行,可以看看glibc的 backtrace()和backtrace_symbols() 函数。


Answer6:

你可以使用kill(2)发送信号:

#include

#include

int kill(pid_t pid, int sig);

像这样:

kill(getpid(), SIGSEGV);

你可能感兴趣的:(翻译:How to programmatically cause a core dump in C/C++)