一 GDB
gdb - The GNU Debugger,即GNU调试器,该工具帮助你查询一个程序内部执行的过程
二 支持参数
action | eg | 描述 |
---|---|---|
b | b ngx_epoll_process_events | 在该函数入口打断点 |
b file.c:N | b nginx.c:100 | 在文件100行打断点 |
info | info proc (breakpoints) | 显示跟踪进程id(断点)信息 |
c | c | 从一个断点执行到下一个断点 |
n | n | 逐行执行代码,在遇到函数时,不进入函数内部执行 |
s | s | 逐行执行代码,在遇到函数时,进入函数内部执行 |
r | r | run 直接调到断点处 |
d | d n | 删除断点 |
bt | 打印调用堆栈(stack trace) | |
q | 退出gdb |
三 调试场景
1 启动你的程序,指定任意可以影响程序行为的参数
2 让程序在指定的条件停住.
3 测试程序停止的时候发生了什么。
4 改变程序内部的变量,来改正程序的错误继续执行
四 调试过程
为了方便跟踪,在nginx.conf 里 设置worker_processes 为 1,然后命令行查询nginx worker进程ID
[@bx16-7-88 ~]# ps aux | grep nginx
root 24997 0.0 0.0 112704 980 pts/53 S+ 19:23 0:00 grep --color=auto nginx
root 29240 0.0 0.0 20824 952 ? Ss Mar24 0:00 nginx: master process /usr/local/nginx/sbin/nginx
www 29241 0.0 0.1 21276 2132 ? S Mar24 0:00 nginx: worker process
[@bx16-7-88 ~]# gdb
(gdb)
(gdb) attach 29241
Attaching to process 29241
(gdb) b ngx_epoll_process_events
(gdb)Breakpoint 1 at 0x432087: file src/event/modules/ngx_epoll_module.c, line 785.
(gdb) info breakpoints
Num Type Disp Enb Address What
1 breakpoint keep y 0x000000000042a245 in ngx_event_accept at src/event/ngx_event_accept.c:24
breakpoint already hit 3 times
2 breakpoint keep y 0x000000000043d66c in ngx_http_init_connection at src/http/ngx_http_request.c:207
breakpoint already hit 2 times
3 breakpoint keep y 0x000000000043f5cf in ngx_http_wait_request_handler at src/http/ngx_http_request.c:386
breakpoint already hit 2 times
(gdb) b ngx_http_process_request
Breakpoint 6 at 0x43cd56: file src/http/ngx_http_request.c, line 1878.
(gdb) b ngx_http_handler
Breakpoint 7 at 0x4354c7: file src/http/ngx_http_core_module.c, line 804.
(gdb) b ngx_http_core_run_phases
Breakpoint 8 at 0x435480: file src/http/ngx_http_core_module.c, line 847.
(gdb) b ngx_http_output_filter
Breakpoint 9 at 0x439eb8: file src/http/ngx_http_core_module.c, line 1761.
(gdb) c
Continuing.
Breakpoint 1, ngx_event_accept (ev=0x8ab210) at src/event/ngx_event_accept.c:24
24 {
(gdb) c
Continuing.
Breakpoint 2, ngx_http_init_connection (c=0x8739e0) at src/http/ngx_http_request.c:207
207 {
(gdb) c
Breakpoint 8, ngx_http_core_run_phases (r=r@entry=0x80e1d0) at src/http/ngx_http_core_module.c:847
847 {
(gdb) n
852 cmcf = ngx_http_get_module_main_conf(r, ngx_http_core_module);
(gdb) n
854 ph = cmcf->phase_engine.handlers;
(gdb) n
856 while (ph[r->phase_handler].checker) {
(gdb) n
244 delta = ngx_current_msec - delta;
(gdb) n
249 ngx_event_process_posted(cycle, &ngx_posted_accept_events);
(gdb) p delta
$3 = 1324688
(gdb) q
A debugging session is active.
Inferior 1 [process 29241] will be detached.
Quit anyway? (y or n) y
Detaching from program: /usr/local/nginx/sbin/nginx, process 29241
五 nginx启动及处理脑图
欢迎一起学习!
延伸阅读
【深度】nginx strace和gstack源码调试
nginx源码注释项目
参考文档
1 GDB debugger