ubuntu gdb多线程调试与例程

借鉴:https://blog.csdn.net/snow_5288/article/details/72982594

1、调试代码 单线程

 

   /**************************************
   *文件说明:process.c
   *作者:段晓雪
   *创建时间:2017年06月10日 星期六 10时59分14秒
   *开发环境:Kali Linux/g++ v6.3.0
   ****************************************/
   
   #include<stdio.h>
   #include<stdio.h>
   #include<unistd.h>
   #include<sys/types.h>
   #include<sys/wait.h>
 
   int main()
   {
      pid_t pid = fork();//创建子进程
 
      if(pid == -1)
      {
          perror("fork error");
          return -1;
      }
      else if(pid == 0)//child
      {
          printf("i am a child:my pid is %d,my father is %d\n",getpid(),getppid());
      }
      else//father
      {
          printf("i am a father:my pid is %d\n",getpid());
          wait(NULL);//等待子进程
      }
 
      return 0;
 
  }

 终端输入:

gcc -o process process.c -g

 gbd  process 就可以进行调试

终端开头变为(gdb) 

用l/list命令查看源代码(按enter翻页),分别在子进程和父进程相应位置下断点:

 

(gdb) b 24 (打断点位置行号)

 

(gdb) r (运行程序的意思)

 

(gdb) info inferiors (inferior有时候会在进程没有启动的时候就存在)

 

(gdb) continue (断点中断继续运行)

 

2、例程2

 

#include<stdio.h>
#include<pthread.h>
 
void *pthread1_run(void *arg)
{
    int count=10;
    while(count--)
    {
        sleep(1);
        printf("i am new pthread1 %lu\n",pthread_self());
    }
    pthread_exit(NULL);
    return 0;
}
 
void *pthread2_run(void *arg)
{
    int count=10;
    while(count--)
    {
        sleep(1);
        printf("i am new pthread2 %lu\n",pthread_self());
    }
    pthread_exit(NULL);
    return 0;
}
 
int main()
{
    pthread_t tid1;
    pthread_t tid2;
    pthread_create(&tid1,NULL,pthread1_run,NULL);
    pthread_create(&tid2,NULL,pthread2_run,NULL);
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    return 0;
}
 终端输入:gcc testtid.c -lpthread -o testtid -g
gdb testtid

上面有的命令都可以用

 

(gdb)info threads  (显示可以调试的所有线程 *为所在的线程)

存在两个以上的线程可以进行线程转换

 

(gdb)thread ID (ID 对应修改  切换当前调试的线程为指定ID的线程。)

 

3、带有参数输入的多线程:

不带是参数输入终端运行:

(gdb) r (运行程序的意思)
带有参数输入终端运行 :(gdb) r  文件位置  ,即可

 

4、core文件

在终端输入:

ulimit -c unlimited 

 

程序正常运行 ,不是在gdb上运行,例子1为例,

终端输入:

 

$gcc -o process process.c -g
$  ./process

在相应的文件夹就可以看到core文件。

利用gdb打开

$ gdb process  core

 

可以对该错误进行跟总调试:
$(gdb) bt 
查看线程栈结构

 

$(gdb) where
 查看当前位置

 

$(gdb) thread apply all bt
让所有被调试的线程都执行同一个命令,就是打印堆栈信息

 

 

$(gdb) thread apply 1 bt
只让线程编号为1的线程打印堆栈信息
 

锁定线程并查看当前锁定的线程

 

 

 

 

 

 

https://blog.csdn.net/tjcwt2011/article/details/80272037
linux程序莫名异常怎么查
 

 

 

posted @ 2019-10-28 20:39  我从花中来  阅读(339)  评论(0编辑  收藏  举报