python - 如何将 gdb 附加到从 Python 脚本启动的子进程?

标签 python gdb

我有以下 Python 3 脚本

foobar.py:

#!/usr/bin/python3

import subprocess
import sys

p = subprocess.Popen(["./foobar"], stdin=subprocess.PIPE, shell=False)
sys.stdin.read(1)
p.stdin.write("f".encode())
p.stdin.flush()
sys.stdin.read(1)

它启动从以下文件 foobar.c 使用 -g 选项编译的程序 foobar:

foobar.c:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char c;

    if (EOF == scanf("%c", &c)) {
        perror(NULL);
        exit(1);
    }

    printf("received char %c\n", c);
    return(0);
}

我启动脚本,它等待我输入一个字符,我按Enter,然后我得到f:

>./foobar.py

received char f

好的,我想要的是使用调试器 gdb 检查 foobar。这就是 sys.stdin.read(1) 的用途:我希望开始

>./foobar.py

然后,在另一个终端中,找到foobar的进程ID,并运行

>gdb Attachpid-ex='b foobar.c:12'

然后我希望像以前一样在第一个终端中按 Enter,然后 C 程序会吃掉输入并停止在第 12 行,即 printf , 按照要求。

但这样不行 - 我按了 Enter 但没有任何反应,程序 foobar 没有移动,它仍然在 scanf 处等待>。

如何才能在 printf 处停止?

最佳答案

How to do it so that I can stop at printf ?
gdb attach pid -ex='b foobar.c:12'

尚不清楚 gdb Attach pid -ex ...确切含义是什么。

您是否忘记继续下级进程(该进程被附加到它的 GDB 停止)?

这对我来说效果很好:

$ gdb -q -ex "attach $(pidof foobar)" -ex 'break foobar.c:12' -ex continue
Attaching to process 88748
Reading symbols from /tmp/stdin/foobar...done.
0x00007f9b78811330 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
81  ../sysdeps/unix/syscall-template.S: No such file or directory.
Breakpoint 1 at 0x400664: file foobar.c, line 12.
Continuing.

...GDB 就坐在这里(如预期的那样)。在 foobar.py 窗口中按 Enter 后:

Breakpoint 1, main () at foobar.c:12
12      printf("received char %c\n", c);

关于python - 如何将 gdb 附加到从 Python 脚本启动的子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46513780/

相关文章:

python - 解析平滑视频 list 文件?

c++ - gdb:tstart 错误 "You can' 的含义 t 当你的目标是 `exec' 时执行此操作“

c - gdb 重复 "no symbol table is loaded"

c++ - 在 Mac OS X 上使用 Eclipse CDT 调试远程 Linux 应用程序

c++ - 嵌入 GDB 断点

python - sqlite3中整数主键没有自动增量

python - 导入 tensorflow "AlreadyExistsError: Another metric with the same name already exists."时出错

python - Pandas groupby 标识另一列中具有最大值的元素

python - 如何仅针对 PR 中更改的功能运行覆盖率报告?

c - 使用gdb调试exe