linux下代码生成core文件

来源:互联网 发布:13年总决赛詹姆斯数据 编辑:程序博客网 时间:2024/05/17 03:32

我们都知道在linux环境下,通过ulimit -c size 命令能方便的打开或关闭coredump功能,从而生成core文件,便于调试。但是对于如何用代码控制生成core文件,可能很多人就不知道了。我们一起来看下,其实也很简单。

首先需要了解两个函数:

       int getrlimit(int resource, struct rlimit *rlim);       int setrlimit(int resource, const struct rlimit *rlim);

这两个函数可以对系统的一些资源进行设置,比如打开的进程数、文件数、生成的core文件大小等。

对于我们关心的生成core文件,需要将第一个参数int resource设置为RLIMIT_CORE即可。这样通过第二参数中的设置,可以很方便的对生成的core大小进行控制。

示例代码如下:

test.h文件:

#include <sys/time.h>#include <sys/resource.h>int set_core(int core_size){   struct rlimit rlim;   rlim.rlim_cur = core_size;   rlim.rlim_max = core_size;  int ret = setrlimit(RLIMIT_CORE, &rlim);  if( ret != 0 ){ printf("setrlimit | set core size failed, ret=%d\n", ret); return ret;} printf("setrlimit | set core size successfully, ret=%d, core_size=%d\n", ret, core_size);return ret;}int get_core(int* limit_cur, int* limit_max){   struct rlimit rlim;  int ret = getrlimit(RLIMIT_CORE, &rlim);  if( ret != 0 ){ printf("getrlimit | get core size failed, ret=%d\n", ret); return ret;} printf("getrlimit | get core size successfully, ret=%d, limit_cur:%lu, limit_max:%lu \n", ret, rlim.rlim_cur, rlim.rlim_max); *limit_cur = (int)rlim.rlim_cur; *limit_max = (int)rlim.rlim_max;return ret;}int test_core(){  int set_core_size = 1024;  int get_cur = 0;  int get_max = 0;  get_core(&get_cur, &get_max);  set_core(set_core_size); get_core(&get_cur, &get_max);   return 0;}
test.cpp文件:

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include "test.h" int main(){     test_core();     int* p = NULL;     *p = 123;      return 0;}


输出:

root@atstest:/home/demo_test# ./test 
getrlimit | get core size successfully, ret=0, limit_cur:20480, limit_max:20480 
setrlimit | set core size successfully, ret=0, core_size=1024
getrlimit | get core size successfully, ret=0, limit_cur:1024, limit_max:1024 
段错误 (核心已转储)

生成的文件:

root@atstest:/home/demo_test# ll
ls: 3·????? 10496
-rw-r----- 1 root root 10723328  4月 17 19:02 core
-rwxr--r-- 1 root root       22  4月 17 15:27 make.sh
-rwxr-xr-x 1 root root     8748  4月 17 19:24 test
-rw-r--r-- 1 root root      276  4月 16 19:31 test.cpp
-rw-r--r-- 1 root root     1389  4月 16 16:06 test.h


我们看到,在当前目录下生成了core文件,大小是10723328字节,后续就可以使用这个core文件进行调试了。这样的方法对于在线服务的程序来说尤为有用,尤其是当崩溃的几率很低的时候,省下大量的时间去蹲守进程崩溃。


不过这里面也有一个问题,我目前也没有搞清楚,就是当我在set_core函数里面设置的core文件大小是1024字节时,生成的core文件还是10723328,好像做的大小设置没有生效,不知道为什么。有知道原因的大虾可以@我沟通交流。



1 0
原创粉丝点击