Linux 执行c程序和core文件简单解读

C源码编译执行测试:

在Linux上编译C源码需要gcc编译器,这也是为啥在编译安装软件的时候需要先安装gcc,简单测试如下:

yum -y install gcc
# 安装gcc编译器
cd /tmp/
cat >helloWorld.c<<EOF
#include <stdio.h>
int main()
{
  printf("Hello world!\n");
}
EOF
# 写一个C程序源文件
# 该程序只加载stdio.h,标准的输入输出头文件
# 该程序只有一个简单的main函数,函数打印Hello world字符串
gcc -o helloWorld helloWorld.c
# 将C源文件编译成可执行文件
./helloWorld
# Hello world!
# 这也是系统基础命令,如ls、cd等等的命令的实现方式
# 使用C编写,gcc编译成可执行文件,然后存入系统环境变量所在目录

core dump:

C程序在执行过程中,如果崩溃,会生成一个core文件,记录崩溃的线程、堆栈等信息
需要做设置,讲core文件保存下来(这就是所谓的core dump 内核转储),以便后续的排障:

ulimit -c unlimited
# 临时打开内核转储,默认是关闭的
# ulimit -c 为0 表示内核转储是关闭的,不为0则是能够保留下来的core文件容量限额

简单写一个会崩溃的C程序,使用gdb命令查看core文件信息:

cat >test.c<<EOF
#include <stdio.h>
int main (int argc, char *argv[])
{
  int *p = NULL;
  *p = 0;
  // 崩溃语句
  return 0;
}
EOF
gcc -o test test.c
./test
# Segmentation fault (core dumped)
# 报错,当前目录下生成core.PID文件

yum -y install gdb
# 使用gdb工具解读core文件
# gdb test core.PID
# 使用gdb解读可执行文件test生成的core文件

CoreFile=core.2279
# 传入core文件名
ExecFile=$(file ${CoreFile}|awk -F\' '{print $2}')
# 获取生成core文件的可执行程序名
gdb -q --batch --ex "set height 0" -ex "thread apply all bt full" ${ExecFile} ${CoreFile}
# 非交互式使用gdb命令获取core文件中记录的信息:
# ...
# Core was generated by `./test'.
# Program terminated with signal 11, Segmentation fault.
# #0  0x000000000040045f in main ()
#
# Thread 1 (Thread 2279):
# #0  0x000000000040045f in main ()
# No symbol table info available.
# 将以上信息提供给C程序的开发人员即可

[TOC]

猜你喜欢

转载自blog.csdn.net/zwjzqqb/article/details/80022086