在CentOS或者suse等Linux系统中默认是关闭coredump核心转储的,也就不会产生core文件。由于在C/C++开发中会用到gdb调试,所以需要开启coredump功能。下面是具体的配置命令,可以保存为一个简单的shell脚本执行。
#!/bin/bash
### Filename: coredumpshell.sh
### Description: enable coredump and format the name of core file on centos system
# enable coredump whith unlimited file-size for all users
echo -e "\n# enable coredump whith unlimited file-size for all users\n* soft core unlimited" >> /etc/security/limits.conf
# set the path of core file with permission 777
cd /mydata && mkdir corefile && chmod 777 corefile
# format the name of core file.
# %% – 符号%
# %p – 进程号
# %u – 进程用户id
# %g – 进程用户组id
# %s – 生成core文件时收到的信号
# %t – 生成core文件的时间戳(seconds since 0:00h, 1 Jan 1970)
# %h – 主机名
# %e – 程序文件名
echo -e "/mydata/corefile/core-%e-%s-%u-%g-%p-%t" > /proc/sys/kernel/core_pattern
# suffix of the core file name
echo -e "1" > /proc/sys/kernel/core_uses_pid
在Linux终端上执行完上面的脚本后,退出并重新登录即可生效。可以通过[root@typecodes ~]# ulimit -a
命令查看效果,如下图所示:
最后,写了一个简单C程序测试CentOS是否生成了相应的core文件。
[root@typecodes test]# vim test.c
#include <stdio.h>
int main( int argc, char * argv[] )
{
char a[1];
scanf( "%s", a );
return 0;
}
使用命令gcc test.c -o test
编译后执行,然后故意输入错误的数据,让进程报错。这时,在/mydata/corefile/
目录就生成了相应的core文件core-test-11-0-0-27124-1434029850
。
//一条命令查看是否能产生coredump
kill -s SIGSEGV $$