打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Linux下发生段错误时如何产生core文件

Linux下发生段错误时如何产生core文件

   Linux下的C程序常常会因为内存访问错误等原因造成segment fault(段错误),此时如果系统core dump功能是打开的,那么将会有内存映像转储到硬盘上来,之后可以用gdb对core文件进行分析,还原系统发生段错误时刻的堆栈情况。这对于我们发现程序bug很有帮助。

  使用ulimit -a可以查看系统core文件的大小限制;使用ulimit -c [kbytes]可以设置系统允许生成的core文件大小,例如

  ulimit -c 0 不产生core文件

  ulimit -c 100 设置core文件最大为100k

  ulimit -c unlimited 不限制core文件大小

  先看一段会造成段错误的程序:

  #include

  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

  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手册。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
linux core文件 ulimit调试程序。
linux下产生core文件以及不产生core文件的条件
使用gdb和core dump迅速定位段错误(完)
GDB调试core文件样例(如何定位Segment fault)
Linux 常用命令:开发调试篇
【精品博文】linux编程之 Core Dump
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服