使用 core dump 查找程序遇到严重问题退出的原因
不使用 ulimit 命令,在程序中使用 API 开启 core dump。注意:只对当前程序有效。
#include <sys/resource.h>int enableCoreDump(void){struct rlimit r_old, r_new;getrlimit(RLIMIT_CORE, &r_old);printf("r_old.rlim_cur : %d, r_old.rlim_max : %d\n", r_old.rlim_cur, r_old.rlim_max);r_new.rlim_cur = RLIM_INFINITY;r_new.rlim_max = RLIM_INFINITY;if (setrlimit(RLIMIT_CORE, &r_new) != 0) {getrlimit(RLIMIT_CORE, &r_old);printf("r_old.rlim_cur : %d, r_old.rlim_max : %d\n", r_old.rlim_cur, r_old.rlim_max);}r_new.rlim_cur = r_old.rlim_max;r_new.rlim_max = r_old.rlim_max;setrlimit(RLIMIT_CORE, &r_new);getrlimit(RLIMIT_CORE, &r_old);printf("r_old.rlim_cur : %d, r_old.rlim_max : %d\n", r_old.rlim_cur, r_old.rlim_max);return 0;}
编译程序时注意使用 -g 标志,加入调试信息,否则调试时只能看到函数地址,看不到函数名。
程序遇到严重错误退出后,会在启动程序的目录下生成 core 文件。将 core 文件复制到主机,用交叉编译器提供的gdb 打开。
arm-linux-gdb ./a.out core
输入 where,即可看到函数在哪退出的,以及函数调用栈。下面是输入 where 后,输出的函数调用栈:
Program terminated with signal SIGSEGV, Segmentation fault.#0 0x00008c48 in cJSON_GetArrayItem (array=<optimized out>, item=171880)at cJSON.c:662662 cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;}(gdb) where#0 0x00008c48 in cJSON_GetArrayItem (array=<optimized out>, item=171880)at cJSON.c:662#1 0x0000b8dc in addItem (cacheArray=0xe1a03000, statusArray=0x29f68,mode=CACHE_MODE_SYNC) at CacheManager.c:162#2 0x0000b8dc in addItem (cacheArray=0xe1a03000, statusArray=0x29f68,mode=CACHE_MODE_SYNC) at CacheManager.c:162#3 0x00000000 in ?? ()Backtrace stopped: frame did not save the PC
浙公网安备 33010602011771号