我有以下 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 Attach
pid-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 attachpid
-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/