http://hi.baidu.com/wrap/blog/item/910b4709841f1dc53bc76306.html
How to use gdb to catch exit situation for programs
Some times, our programs exit after running about days or months without any log information left for us to debug. It's really headache to determine where program is exit, unless enough logs are printed. Then that's the question: how can we resolve it now?
Here is a tips to do this:
We want to get the back-trace of function2 as it's exit with 1.
====================================
hickey@ubuntu:~/test$ cat exit.c
#include <stdlib.h>
int
function1(int i){
//abort();
}
int
function2(int i){
exit(1);
abort();
}
int
main() {
function1(1);
function2(2);
abort();
}
====================================
GDB file:
====================================
hickey@ubuntu:~/test$ cat gdb.ini
set logging on
handle SIGHUP nostop
handle SIGPIPE noprint nostop
b main
r
b _exit
c
bt full
quit
====================================
Result:
====================================
hickey@ubuntu:~/test$ gdb ./a.out -x gdb.ini
GNU gdb 6.8-debian
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-linux-gnu"...
Breakpoint 1 at 0x40056e: file exit.c, line 16.
Breakpoint 1, main () at exit.c:16
16 function1(1);
Breakpoint 2 at 0x7fd1f7d7c090
Breakpoint 2, 0x00007fd1f7d7c090 in _exit () from /lib/libc.so.6
#0 0x00007fd1f7d7c090 in _exit () from /lib/libc.so.6
No symbol table info available.
#1 0x00007fd1f7d0a765 in exit () from /lib/libc.so.6
No symbol table info available.
#2 0x000000000040056a in function2 (i=2) at exit.c:10
No locals.
#3 0x0000000000400582 in main () at exit.c:17
No locals.
The program is running. Exit anyway? (y or n) [answered Y; input not from terminal]
====================================
Another question, if we want to use gdb to attach an existing gdb that already attached with an application's pid, the solution is attach gdb with gdb and the attach application pid again:
====================================
1) gdb <gdb> <gdb_pid> in terminal
hickey@d001:~$ gdb gdb 12409
2) attach application pid
(gdb) attach 12415
A program is being debugged already. Kill it? (y or n) y
Attaching to program: /usr/bin/gdb, process 12415
0x00000000004005d6 in ?? ()
(gdb) bt
3) then you got it with gdb
====================================