【gdb】设置读观察点
正文
设置读观察点
1. 例子
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int a = 0;
void *thread1_func(void *p_arg)
{
while (1)
{
a++;
sleep(10);
}
}
void *thread2_func(void *p_arg)
{
while (1)
{
a++;
sleep(10);
}
}
int main(void)
{
pthread_t t1, t2;
pthread_create(&t1, NULL, thread1_func, "Thread 1");
pthread_create(&t2, NULL, thread2_func, "Thread 2");
sleep(1000);
return 0;
}
gdb可以使用“rwatch
”命令设置读观察点,也就是当发生读取变量行为时,程序就会暂停住。以上面程序为例:
(gdb) start
Temporary breakpoint 1 at 0x4005f3: file a.c, line 19.
Starting program: /data2/home/nanxiao/a
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
Temporary breakpoint 1, main () at a.c:19
19 pthread_create(&t1, NULL, thread1_func, "Thread 1");
(gdb) rw a
Hardware read watchpoint 2: a
(gdb) c
Continuing.
[New Thread 0x7ffff782c700 (LWP 5540)]
[Switching to Thread 0x7ffff782c700 (LWP 5540)]
Hardware read watchpoint 2: a
Value = 0
0x00000000004005c6 in thread1_func (p_arg=0x40071c) at a.c:10
10 printf("%d\n", a);
(gdb) c
Continuing.
0
Hardware read watchpoint 2: a
Value = 0
0x00000000004005c6 in thread1_func (p_arg=0x40071c) at a.c:10
10 printf("%d\n", a);
(gdb) c
Continuing.
0
Hardware read watchpoint 2: a
Value = 0
0x00000000004005c6 in thread1_func (p_arg=0x40071c) at a.c:10
10 printf("%d\n", a);
可以看到,使用“rw a
”命令(rw
是rwatch
命令的缩写)以后,每次访问a
的值都会让程序停下来。
需要注意的是rwatch
命令只对硬件观察点才生效
参考资料
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构