问题程序:
segment.c
- #include <stdio.h>
- #include <signal.h>
- #include <unistd.h>
- #include <stdlib.h>
- void func()
- {
- char *p = NULL;
- *p = 3;
- }
- main()
- {
- func();
- return;
- }
编译:
- gcc -g -o segment segment.c
Core文件:
1. 查看系统是否允许生成core文件
- #ulimit -a
- core file size (blocks, -c) 0
core文件大小限制为0,不能生成core文件。
2. 使用如下命令取消限制,使系统能生成core文件
或者指定core文件大小,如1K
- ulimit -c unlimited
- ulimit -c 1024
执行程序:
- # ./segment
- egmentation fault (core dumped)
GDB调试:
- # gdb ./segment core
- GNU gdb (GDB) 7.1-ubuntu
- Copyright (C) 2010 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 "i486-linux-gnu".
- For bug reporting instructions, please see:
- <http://www.gnu.org/software/gdb/bugs/>...
- Reading symbols from /home/duanbb/test/segment/segment...done.
- [New Thread 3655]
- warning: Can't read pathname for load map: Input/output error.
- Reading symbols from /lib/tls/i686/cmov/libc.so.6...Reading symbols from /usr/lib/debug/lib/tls/i686/cmov/libc-2.11.1.so...done.
- done.
- Loaded symbols for /lib/tls/i686/cmov/libc.so.6
- Reading symbols from /lib/ld-linux.so.2...Reading symbols from /usr/lib/debug/lib/ld-2.11.1.so...done.
- done.
- Loaded symbols for /lib/ld-linux.so.2
- Core was generated by `./segment'.
- Program terminated with signal 11, Segmentation fault.
- #0 0x080483c4 in func () at segment.c:10
- 10 *p = 3;
可以清楚地看到,程序在第10行代码,func()函数内,执行"*p = 3"时发生了segment错误
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Core文件的命名和路径
默认情况下core文件名即为"core",文件路径:运行可执行文件时,环境所在的目录
两个控制文件
(1) /proc/sys/kernel/core_uses_pid
0: 默认值,生成的文件名不会带上PID后缀
1: 文件名带上PID后缀,如"core.2976"
修改方法: "echo 1 > /proc/sys/kernel/core_uses_pid"
(2) /proc/sys/kernel/core_pattern
用来控制文件名格式
默认值: core
假设将其值改变为:"/home/duanbei/corefile/core-%e-%p-%t", 那么所有的core文件将保存在"/home/duanbei/corefile"目录下,文件名格式为“core-程序名-pid-时间戳”
格式参数列表
- %p - insert pid into filename
- %u - insert current uid into filename
- %g - insert current gid into filename
- %s - insert signal that caused the coredump into the filename
- %t - insert UNIX time that the coredump occurred into filename
- %h - insert hostname where the coredump happened into filename
- %e - insert coredumping executable name into filename
注:如果设置了“%p”,而“/proc/sys/kernel/core_uses_pid”值又为1,则不会添加PID后缀,因文件名中已含该信息
PS:
要生成core文件,就不要在程序中用signal()捕获‘SIGSEGV’信号了,不然生成不了core文件