1. 默认设置下,在调试多进程程序时GDB只会调试主进程。但是GDB(>V7.0)支持多进程的分别以及同时调试,换句话说,GDB可以同时调试多个程序。只需要设置follow-fork-mode(默认值:parent)和detach-on-fork(默认值:on)即可。
follow-fork-mode detach-on-fork 说明 parent on 只调试主进程(GDB默认) child on 只调试子进程 parent off 同时调试两个进程,gdb跟主进程,子进程block在fork位置 child off 同时调试两个进程,gdb跟子进程,主进程block在fork位置 设置方法:set follow-fork-mode [parent|child] set detach-on-fork on|【off】 查询正在调试的进程:info inferiors 切换调试的进程: inferior <infer number> 测试代码: 1 #include<stdio.h> 2 #include<unistd.h> 3 #include<sys/types.h> 4 5 6 int main() 7 { 8 pid_t id; 9 id=fork(); 10 if(id=0){//child 11 printf("%d,%d\n",getpid(),getppid()); 12 exit(0); 13 }else {//father 14 printf("%d,%d\n",getpid(),getppid()); 15 } 16 return 0; 17 } GDB调节多线程: 在多线程编程时,当我们需要调试时,有时需要控制某些线程停在断点,有些线程继续执行。有时需要控制线程的运行顺序。有时需要中断某个线程,切换到其他线程。这些都可以通过gdb实现。 GDB默认支持调试多线程,跟主线程,子线程block在create thread。先来看一下gdb调试多线程常用命令
info threads:显示可以调试的所有线程。gdb会为每个线程分配一个ID(和tid不同),编号一般从1开始。后面的ID是指这个ID。 thread ID:切换当前调试的线程为指定ID的线程。 代码测试: 1 #include<stdio.h> 2 #include<unistd.h> 3 #include<sys/types.h> 4 #include<pthread.h> 5 6 7 8 void* thread_run1(void* val) 9 { 10 int i=3; 11 while(i){ 12 i--; 13 printf("i am run1!! %d,%u\n",i,pthread_self()); 14 sleep(1); 15 } 16 return NULL; 17 } 18 void* thread_run2(void* val) 19 { 20 int m=5; 21 while(m){ 22 m--; 23 printf("i am run2!! %d, %u\n",m,pthread_self()); 24 sleep(2); 25 } 26 return 0; 27 } 28 int main() 29 { 30 pthread_t tid1; 31 pthread_t tid2; 32 33 pthread_create(&tid1,NULL,thread_run1,NULL); 34 pthread_create(&tid2,NULL,thread_run2,NULL); 35 36 pthread_join(tid1,NULL); 37 pthr