手贱写个bug,索性看看gdb。
首先写个简单的多线程小程序用于测试:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *function(void *p)
{
unsigned int count = 0;
while(1)
{
printf("In function: %d\n\n", count);
sleep(1);
count++;
#if 0
if(count == 5)
{
int * a = NULL;
(*a)++;
}
#endif
}
}
#if 1
int main()
{
pthread_t thread;
pthread_create(&thread, NULL, function, NULL);
//pthread_join(thread, NULL);
unsigned int main_count = 0;
while(1)
{
printf("In main: %d\n", main_count);
sleep(1);
main_count++;
}
printf("main return \n");
return 0;
}
#endif
基本的gdb操作不在此赘述,以下是attach 实录:
-
在编译源码的时候切记加 -g 选项,否则 执行
list
冒出个No symbol table is loaded
-
编译完成后运行即可,执行
./exe
(exe是我重命名后的可执行程序)
-
执行
ps -ef | grep exe
获取 exe pid
-
执行
gdb
+attach 29708
,其中29708是上图中exe的pid
-
左侧为exe运行输出,此时运行中断,等到attach 的 gdb 命令行给指令,比如我执行
n
,如下图
- 可以尝试一些基本操作,如:
- 我想实现两点:
-
- 打印count的值,这个很容易实现,利用
p
(单次打印) 或display
(多次打印) 均可实现。
- 打印count的值,这个很容易实现,利用
-
- 希望程序一直运行,这个用到了
command
命令:
在11行设置一个断点,断点编号为5,执行command 5
- 希望程序一直运行,这个用到了
> p count #打印 count 的值
> c #continue
> end #结束command的输入
此时执行info b
可以看到,在断点5下多了两行命令。
执行c
:
此时程序就会在断点5处中断,执行p count
,然后执行c
直到下次触发中断。
不过,这样也不是我想要的,目前不知道什么原因,这样的实现方式只能执行9次,如下图
这只是减少了工作量,可还需要人为干预。之后又尝试了silent
:
实现效果:
依旧需要人为干预,难受。。。
先到这吧,后期有什么再补充。