GDB调试单进程及多进程程序

本文介绍了如何使用GDB调试单进程和多进程程序,包括直接调试法和附着调试法。在多进程调试中,强调了插桩、运行多进程和在新终端窗口调试的重要性。此外,还列举了GDB的一些常用指令,如断点管理、查看调用堆栈和变量操作等。
摘要由CSDN通过智能技术生成

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
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值