gdb调试fork多进程

使用gdb调试fork多进程时,可能会根据需要调试父进程或者子进程。先介绍下需要使用的命令:

  1. follow-fork-mode命令有两个选项parent/child,代表调试调试父进程还是子进程

  2. detach-on-fork命令也有两个选项on/off,代表是否在调试父进程或者子进程时,是否只调试一个进程。

  3. Info inferior查询当前的所有进程

  4. inferior [number_id]

前两个命令可以进行排列使用:

follow-fork-mode detach-on-fork Description
parent on 只调试父进程(GDB 模式)
child on 只调试子进程
parent off 同时调试两个进程, GDB 跟父进程,子进程阻塞在 fork 处
child off 同时调试两个进程, GDB 跟子进程,父进程阻塞在 fork 处
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
    pid_t pid = fork();
    if (pid == 0) {
        printf("This is child\n");
    } else {
        pid_t ppid = getpid();
        printf("This is parent(%d), child pid=%d\n", ppid, pid);
        wait(ppid);
        
    }
    return 0;
}

调试过程如下:

  1. 查看当前follow-fork-mode和detach-on-fork的模式
(gdb) show follow-fork-mode
Debugger response to a program call of fork or vfork is "parent".
(gdb) show detach-on-fork
Whether gdb will detach the child of a fork is on.
  1. 根据自己的需要设置调试模式(我调试时设置成parent/off的模式)
(gdb) set detach-on-fork off
  1. 设置调试断点
(gdb) b test_fork.c:9
Breakpoint 1 at 0x11e3: file ./test_fork.c, line 9.
(gdb) b test_fork.c:12
Breakpoint 2 at 0x11f9: file ./test_fork.c, line 12.
  1. 运行程序并查看当前调试的进程
(gdb) r
Starting program: /home/cambricon/code/OS/arm-abi/fork 
[New inferior 2 (process 385421)]
Reading symbols from /home/cambricon/code/OS/arm-abi/fork...
Reading symbols from /usr/lib/debug/.build-id/07/02430aef5fa3dda43986563e9ffcc47efbd75e.debug...
Reading symbols from /usr/lib/debug/.build-id/db/0420f708b806cf03260aadb916c330049580b7.debug...


(gdb) info inferior
  Num  Description       Executable        
* 1    process 385417    /home/cambricon/code/OS/arm-abi/fork 
  2    process 385421    /home/cambricon/code/OS/arm-abi/fork 
  1. 切换到子进程并开始运行(切完进程后,直接执行c命令运行到断点处)
(gdb) inferior 3
[Switching to inferior 3 [process 389290] (/home/cambricon/code/OS/arm-abi/fork)]
[Switching to thread 3.1 (process 389290)]


(gdb) c
Continuing.

Thread 3.1 "fork" hit Breakpoint 1, main () at ./test_fork.c:9
9               printf("This is child\n");
posted @ 2024-12-12 16:59  cockpunctual  阅读(61)  评论(0)    收藏  举报