今天, 我们来介绍一个linux中的dmesg命令,事实上, 我们之前用过, 但是没有单独介绍过。
看一下dmesg命令的用途吧:
dmesg命令用会把开机信息存到ring bufer中, 形成一个缓冲, 免得你我来不及看。 在root权限下, 可以用dmesg -c来清楚这个消息。 单纯的一个dmesg命令则是用来输出这些记录信息的。
要注意, 程序core dump之后, 并不一定产生core文件, 此时, 我们的重要目的是: 获取出错堆栈的地址, 而dmesg命令可达此目的。
下面, 我们来看一下经典的dmesg + addr2line
[taoge@localhost test]$ cat test.c -n
1 #include <stdio.h>
2
3 int main()
4 {
5 int *p = NULL;
6 *p = 0;
7
8 printf("bad\n");
9 return 0;
10 }
[taoge@localhost test]$ gcc -g test.c
[taoge@localhost test]$ ./a.out
Segmentation fault (core dumped)
[taoge@localhost test]$
[taoge@localhost test]$
[taoge@localhost test]$
[taoge@localhost test]$ dmesg
a.out[3709]: segfault at 0 ip 080483c9 sp bff75a60 error 6 in a.out[8048000+1000]
[taoge@localhost test]$ addr2line -e a.out 080483c9
/home/taoge/test/test.c:6
[taoge@localhost test]$
可见, 第6行有错, addr2line是我们的老熟人了, 本文主要强调一下dmesg. 当dmesg显示的信息较多时候, 我们通过grep来过滤, 比如 dmesg | grep a.out
在实际开发中, 通常是从日志文件中看到堆栈异常, 同样是为了拿到堆栈出错的地方, 然后用addr2line来定位代码行, 此时, 可以将日志文件看成是dmesg命令的扩展。 在这两种情况下, 我么可以不依赖于core文件, 便可搞定core dump了。
OK, dmesg命令的介绍就先告一段落了。