I have the following Python 3 script
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)
which starts the program foobar compiled from the following file foobar.c with -g option:
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);
}
I start the script, it waits for me to enter a character, I hit Enter, and I get f:
>./foobar.py
received char f
OK, what I would like, is to inspect foobar with the debugger gdb. That is what sys.stdin.read(1) is for: I hoped to start
>./foobar.py
and then, in another terminal, find out the process id of foobar, and run
>gdb attachpid-ex='b foobar.c:12'
then I was hoping to hit Enter in the first terminal as before, and then the C program would eat the input and stop at the line 12, which is printf, as requested.
But it does not work this way - I hit Enter and nothing happens, the program foobar does not budge, it still waits at scanf.
How to do it so that I can stop at printf ?
p.stdin.write("f\n".encode()). Alternatelyp.stdin.close(). That should work.foobar.pyandfoobar.cas given, and they work as shown above. So, they should also work under the debugger - I can insertsys.stdin.read(1)to "stop" so I can attach the debugger, but that's all I can do. I can't go around and change other things. That is the whole point of using the debugger, rather than inserting "print" statements, that you don't change your code. The code above is just an SSCCE, you understand? The "real" code is far bigger.scanfexpects a char + linefeed. So it's not possible to make those both work with the .py and .c code. you can challenge anyone here to make that work, not possible, because of the wayscanfprocesses input.gdbprevents the stream to be closed. by starting without gdb, the input stream is closed & flushed and the C program recieves f+EOF. With the debugger, it doesn't receive EOF or linefeed.