linux ulimit的使用,如何产生core文件,调试段错误?

---恢复内容开始---

下面先简单介绍下ulimit命令:

1. limit -a 可以查看系统各种资源的限制,如: core文件大小,数据段的大小等。

$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 270336
max locked memory       (kbytes, -l) 32
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65535
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 270336
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

以上可以看出,默认的core文件大小为0KB, 即默认不会产生core文件。

可以使用 ulimit -c n 来设置core文件大小,单位是KB。

如:

ulimit -c 100 设置core文件大小是100KB。

ulimit -c unlimited 不限制core文件的大小。

2. 调试段错误程序

下面模拟一个段错误程序:

1 #inlcude <cstring>
2 
3 int main()
4 {
5      std::cout<<"test..."<<std::endl;
6      memset(0,0,10);
7      std::cout<<"test end..."<<std::endl;
8      return 0;   
9 }

编译执行:g++ -g test.cpp

$ ./a.out

start test...

段错误

没有产生core文件。

执行 ulimit -c unlimited

重新运行下程序 :

./a.out

start test...

段错误 (core dumped)

便产生了core文件。

我们可以用gdb a.out core.pid 进行调试core文件

如:

$ gdb a.out core.382 
GNU gdb Fedora (6.8-27.el5)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu"...
Reading symbols from /usr/lib64/libstdc++.so.6...done.
Loaded symbols for /usr/lib64/libstdc++.so.6
Reading symbols from /lib64/libm.so.6...done.
Loaded symbols for /lib64/libm.so.6
Reading symbols from /lib64/libgcc_s.so.1...done.
Loaded symbols for /lib64/libgcc_s.so.1
Reading symbols from /lib64/libc.so.6...done.
Loaded symbols for /lib64/libc.so.6
Reading symbols from /lib64/ld-linux-x86-64.so.2...done.
Loaded symbols for /lib64/ld-linux-x86-64.so.2
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
[New process 382]
#0  main () at test.cpp:8
8               memset(0,0,10);

我们可以发现文件的第8行有问题。