lv6 嵌入式开发-4 gdb调试多进程程序

 1 调试语法

set follow-fork-mode child
set follow-fork-mode parent
set detach-on-fork  on/off
info inferiors 
inferiors  进程序号(1,2,3....)

on: 只调试父进程或子进程的其中一个(根据follow-fork-mode来决定),这是默认的模式

off:父子进程都在gdb的控制之下,其中一个进程正常调试(根据follow-fork-mode来决定),另一个进程会被设置为暂停状态。

info inferiors    显示GDB调试的进程

inferiors  进程序号(1,2,3....)  切换GDB调试的进程

2 示例

使用一段fork代码,代码实现了

#include 
#include 

int main(int argc,char **argv){
    
    pid_t pid;
    printf("before fork\n");
    pid = fork();
    if(pid>0){
       printf("This is father process\n");
       printf("pid=%d\n",(int)pid);
       printf("father after fork\n");
       while(1){
         sleep(1);
         printf("father sleep\n");
       }
   }else if(pid==0){
       printf("This is child process\n");
       printf("pid=%d\n",(int)pid);
       printf("child after fork\n");
       while(1){
          sleep(1);
          printf("child sleep\n");
       }
    }else if(pid<0){
       perror("fork");
       return 0;
    }
   // printf("pid=%d\n",(int)pid);
  //  printf("after fork\n");
  

}

编译

gcc -g -o fork_t fork_t.c

调试

linux@linux:~/Desktop$ gdb fork_t 
GNU gdb (Ubuntu 7.7-0ubuntu3.1) 7.7
......
Reading symbols from fork_t...done.
(gdb) start        //从main函数开始运行
Temporary breakpoint 1 at 0x80484e6: file fork.c, line 10.
Starting program: /home/linux/Desktop/fork_t 

Temporary breakpoint 1, main (argc=1, argv=0xbffff164) at fork.c:10
10			    printf("before fork\n");
(gdb) n
before fork
11				    pid = fork();
(gdb) 
12					    if(pid>0){
(gdb) This is child process
pid=0
child after fork
child sleep
child sleep
child sleep
child sleep
child sleep

如果想切换到父进程或者子进程

linux@linux:~/Desktop$ gdb fork_t 
GNU gdb (Ubuntu 7.7-0ubuntu3.1) 7.7
......
(gdb) start
Temporary breakpoint 1 at 0x80484e6: file fork.c, line 10.
Starting program: /home/linux/Desktop/fork_t 

Temporary breakpoint 1, main (argc=1, argv=0xbffff164) at fork.c:10
10			    printf("before fork\n");
(gdb) set follow-   //tab可补全
follow-exec-mode  follow-fork-mode  
(gdb) set follow-fork-mode 
child   parent  
(gdb) set follow-fork-mode 
child   parent  
(gdb) set follow-fork-mode child //可选child或者parent
(gdb) n
before fork
11				    pid = fork();
(gdb) n
This is father process
pid=8388
father after fork
[New process 8388]
[Switching to process 8388]
12					    if(pid>0){
(gdb) father sleep
father sleep
father sleep
father sleep

如果想同时调试父进程和子进程

(gdb) set follow-fork-mode child
(gdb) n
(gdb) n
(gdb) set detach-on-fork off  //禁用自动分离功能,使得在子进程创建时调试器仍然保持连接并继续调试子进程。相反,如果您希望在子进程创建时自动分离调试器,可以将上述命令中的 "off" 替换为 "on"。
(gdb) info inferiors 
  Num  Description       Executable        
* 2    process 11419     /home/linux/Desktop/fork_t 
  1    process 11415     /home/linux/Desktop/fork_t 
(gdb) inferior 2
[Switching to inferior 2 [process 11419] (/home/linux/Desktop/fork_t)]
[Switching to thread 2 (process 11419)] 
#0  0xb7fdd424 in ?? ()
(gdb) n
(gdb) n
(gdb) inferior 1


你可能感兴趣的:(linux)