需要使用gdb进行调试的时候需要在编译.c文件的时候在gcc后面加上-g
在调试的时候使用gdb ./可执行文件就可以对其进行调试
输入l就可以打印程序的代码在终端上;
设置断点输入b 行号 (break)
让程序运行输入 r(run)
使用print打印程序信息:
让程序从当前位置向后执行输入c(continue)
退出输入q
gdb调试core文件
可以直接定位到段错误的位置;
配置.bashrc文件添加ulimit -c unlimited
当运行程序出现段错误的时候就会在当前文件夹中生成core文件;
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *num = NULL;
*num = 1;
return 0;
}
运行上述代码由于本身指向是空指针,后面对空指针进行赋值,所以产生段错误,生成core
调试core:gdb a.out core
gdb调试正在运行中的程序:
gdb 正在运行的程序 程序进程id号
程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int i= 0;
while(1){
printf("i = %d\n",i++);
sleep(1);
}
return 0;
}
使用gdb a.out -p 99910进行调试;
gdb调试多进程
follow-fork-mode
set follow-fork-mode [parent][child] 设置调试进程(默认父进程)
show follow-fork-mode 查看当前调试模式
detach-on-fork
set detach-on-fork [on][off] 调试当前进程时,其他进程是运行还是挂起(默认)
info inferiors 查询正在调试的进程,带*的是当前正在调试的进程
inferior 切换到要调试的进程
测试代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid = fork();
if(pid == 0){
for(int i = 0;i<10;i++){
printf("this is from child,pid = %d,father is %d\n",getpid(),getppid());
}
exit(1);
}else{
for(int j = 0;j<10;j++){
printf("this is from father,pid = %d, father pid = %d\n",getpid(),getppid());
}
if(wait(NULL) != -1){
printf("child exit success\n");
}
}
return 0;
}
设置调试子进程 set follow-set-follow child/parent
显示调试模式:show follow-fork-mode
调试多线程程序
info threads 查看线程
thread 切换线程
set scheduler-locking off|on|step 设置运行的线程
thread apply ID1 ID2 command 让一个或多个线程执行GDB命令command
thread apply all command 让所有的被调试的线程执行GDB命令command