GDB调试单进程及多进程程序
要使用gdb进行程序的调试,那么在程序的编译时需要加上**-g**选项
GDB调试的两种方式
1、直接调试法:gdb拉取新的进程,从头开始跑程序
gdb a.out // 无参调用
gdb --args a.out ARGS // 含参调用
2、附着调试法:程序正在运行,gdb附着到已经存在的进程上调试
gdb attach pid
注:此时gdb没有拉取进程,而是附着在运行的进程上。一个事实是gdb没有退出,无法kill掉该进程。
第一种方式比较简单,只要进入gdb之后使用gdb常用指令(后文介绍)进行调试即可;而第二种方式比较复杂,我们着重介绍一下第二种方式的应用场景
案例一:调试正在运行的程序
// test.c
#include <iostream>
#include <cmath>
using namespace std;
struct Point
{
int x;
int y;
};
int main()
{
Point po;
po.x = 1;
po.y = 2;
float distance = sqrt(po.x * po.x + po.y * po.y);
getchar();
return 0;
}
进程运行在窗口1,使用窗口2进行调试
窗口1:
xxxx $ gcc -g test.c -lm // 用-g选项编译程序生成可执行文件
xxxx $ ./a.out // 运行程序,程序在getchar()卡住(模拟运行中的程序)
窗口2:
xxxx $ ps -aux | grep a.out // 查看运行a.out进程号
xxxx 36172 0.0 0.0 8224 1080 pts/1 S+ 13:35 0:00 ./a.out
xxxx 36174 0.0 0.0 13136 1068 pts/0 S+ 13:35 0:00 grep a.out
xxxx $ gdb attach 36172 // 使用gdb附着在进程36172
GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
Copyright (C) 2018 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".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
attach: No such file or directory.
Attaching to process 36172
Reading symbols from /home/xxxx/code/test_gdb/a.out...done.
Reading symbols from /lib/x86_64-linux-gnu/libm.so.6...Reading symbols from /usr/lib/debug//lib/x86_64-linux-gnu/libm-2.27.so...done.
done.
Reading symbols from /lib/x86_64-linux-gnu/libc.so.6...Reading symbols from /usr/lib/debug//lib/x86_64-linux-gnu/libc-2.27.so...done.
done.
Reading symbols from /lib64/ld-linux-x86-64.so.2...Reading symbols from /usr/lib/debug//lib/x86_64-linux-gnu/ld-2.27.so...done.
done.
0x00007fb3c806f081 in __GI___libc_read (fd=0, buf=0x55cd3dbf5260, nbyt