如何产生core dump或者core file.

当我的应用程序崩溃或出现段错误的时候,如何产生core文件?
解决方法:

在红帽企业版Linux上默认是不产生core文件。这个限制是在/etc/profile里面设置的:

ulimit -S -c 0 > /dev/null 2>1

有几种方法可以让系统产生core文件。第一个方法是修改/etc/profile里面的ulimit命令,如下:

ulimit -S -c unlimited > /dev/null 2>1

上面的设置允许系统上的所有用户产生没有文件大小限制的core文件。

如果只需要对部分用户或组开放产生core文件的权限,需要编辑/etc/security/limits.conf文件。例如,所有在"devel"组里面的用户可以产生core文件:


#<domain> <type> <item> <value>
@devel soft core <value>

<value>是core文件的最大块大小。 在/etc/security/limits.conf文件里面有配置参数的详细说明。提示,如果想通过limits.conf里面的设置来控制用户是否 可以产生core文件,需要把/etc/profile里面的ulimits设置注释掉:


# No core files by default
# ulimit -S -c 0 > /dev/null 2>1

如果应用是通过daemon命令来启动的,编辑/etc/init.d/functions,注释掉ulimit的设置或改变这行:

ulimit -S -c 0 >/dev/null 2>1

通过上面的设置,应用程序应该可以产生core文件。如果不能产生core文件,请检查您的应用程序是否拥有正确的uid,在程序执行的时候是否有 使用setuid改变程序的uid。 在红帽企业Linux 3上面, 可以通过下面的命令允许使用setuid的应用程序产生core文件:

echo 1 > /proc/sys/kernel/core_setuid_ok

另外,您也可以在应用程序中添加下面的代码来实现:

prctl(PR_SET_DUMPABLE, 1);

默认情况下,core文件会创建在应用程序的工作目录下。如果您想指定core文件存放的目录,您可以执行以下命令(用您要保存的路径替换/tmp):


扫描二维码关注公众号,回复: 1315589 查看本文章

 

echo "/tmp" > /proc/sys/kernel/core_pattern		


例子:

 

#include <stdio.h>

int main()

{

char *ptr="linuxers.cn";

*ptr=0;

}
 

编译运行后结果如下:

 

[leconte@localhost test]$ gcc -g -o test a.c

[leconte@localhost test]$ ./test
 

段错误

此时并没有产生core文件,接下来使用ulimit -c设置core文件大小为无限制,再执行./test程序,结果如下:

 

[leconte@localhost ~]$ ulimit -a

core file size (blocks, -c) 0

[leconte@localhost test]$ ulimit -c unlimited

[leconte@localhost test]$ ulimit -a

core file size (blocks, -c) unlimited

[leconte@localhost test]$ ./test

段错误 (core dumped)

[leconte@localhost test]$ ls -al core.*

-rw------- 1 leconte leconte 139264 01-06 22:31 core.2065

可见core文件已经生成,接下来可以用gdb分析,查看堆栈情况:

[leconte@localhost test]$ gdb ./test core.2065   

GNU gdb Fedora (6.8-27.el5)

Copyright (C) 2008 Free Software Foundation, Inc.

License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software: you are free to change and redistribute it.

There is NO WARRANTY, to the extent permitted by law. Type "show copying"

and "show warranty" for details.

This GDB was configured as "i386-redhat-linux-gnu"...

warning: exec file is newer than core file.

warning: Can't read pathname for load map: Input/output error.

Reading symbols from /lib/libc.so.6...done.

Loaded symbols for /lib/libc.so.6

Reading symbols from /lib/ld-linux.so.2...done.

Loaded symbols for /lib/ld-linux.so.2

Core was generated by `./test'.

Program terminated with signal 11, Segmentation fault.

[New process 2065]

#0 0x0804836f in main () at a.c:6

6 *ptr=0;
 

  从上述输出可以清楚的看到,段错误出现在a.c的第6行,问题已经清晰地定位到了。

  很多系统默认的core文件大小都是0,我们可以通过在shell的启动脚本/etc/bashrc或者~/.bashrc等地方来加入 ulimit -c 命令来指定core文件大小,从而确保core文件能够生成。

  除此之外,还可以在/proc/sys/kernel/core_pattern里设置core文件的文件名模板,详情请看core的官方man手册


注意两点:
gcc -g -o test a.c
     gdb ./test core.2065

 

猜你喜欢

转载自coolwhy1.iteye.com/blog/1331146
今日推荐