CentOS开启coredump转储并生成core文件的配置

在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

# for centos7 system(update 2017.2.3 21:44)
echo -e "/mydata/corefile/core-%e-%s-%u-%g-%p-%t" > /etc/sysctl.conf

# suffix of the core file name
echo -e "1" > /proc/sys/kernel/core_uses_pid

其中的mydata目录改成自己程序的目录就行了
Linux终端上执行完上面的脚本后,退出并重新登录即可生效。可以通过ulimit -a命令查看效果,如下图所示:
在这里插入图片描述
最后,写了一个简单C++程序测试CentOS是否生成了相应的core文件。

#include <stdio.h>

#include <iostream>
using namespace std;

int main()
{
	std::cout << "Hello World" << std::endl;
    char* p = NULL;
    *p = 0;
    return 0;
}

程序的路径是在

/root/gdb_test

先运行一下

echo "/root/gdb_test/core-%e-%p-%t" > /proc/sys/kernel/core_pattern

使用命令g++ test.cpp -o test编译后执行,让进程报错,这时在/root/gdb_test/目录就生成了相应的core文件core-test-4832-1588588728

[root@centos-linux gdb_test]# ./test
Hello World
段错误(吐核)
-rw-------. 1 root root 413696 54 18:38 core-test-4832-1588588728

每次重启CentOS7后,由于proc目录是动态更新的,所以系统会初始化core_pattern的值。如果想永久设置coredump文件为上面的格式,那么需要使用编辑文件 /etc/sysctl.conf ,加入kernel.core_pattern=/mydata/corefile/core-%e-%s-%u-%g-%p-%t,然后使用命令sysctl -p /etc/sysctl.conf重新加载。

#!/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

# format the name of core file.   
# %% – 符号%
# %p – 进程号
# %u – 进程用户id
# %g – 进程用户组id
# %s – 生成core文件时收到的信号
# %t – 生成core文件的时间戳(seconds since 0:00h, 1 Jan 1970)
# %h – 主机名
# %e – 程序文件名    
# for centos7 system(update 2017.4.2 21:44)
echo -e "\nkernel.core_pattern=/mydata/corefile/core-%e-%s-%u-%g-%p-%t" >> /etc/sysctl.conf

# suffix of the core file name
echo -e "1" > /proc/sys/kernel/core_uses_pid

sysctl -p /etc/sysctl.conf
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值