Python Subprocess Hangs
I'm executing the following subprocess... p.call(['./hex2raw', '<', 'exploit4.txt', '|', './rtarget']) ...and it hangs. But if I execute kmwe236@kmwe236:~/CS485/prog3/target26$
Solution 1:
Since you're using redirection and piping, you have to enable shell=True
sp.call(["./hex2raw", "<", "exploit4.txt", "|", "./rtarget"],shell=True)
but it would be much cleaner to use Popen
on both executables and feeding the contents of exploit4.txt
as input. Example below, adapted to your case:
import subprocess
with open("exploit4.txt") as inhandle:
p = subprocess.Popen("./hex2raw",stdin=inhandle,stdout=subprocess.PIPE)
p2 = subprocess.Popen("./rtarget",stdin=p.stdout,stdout=subprocess.PIPE)
[output,error] = p2.communicate()
print(output)
# checking return codes is also a good idea
rc2 = p2.wait()
rc = p.wait()
Explanation:
- open the input file, get its handle
inhandle
- open the first subprocess, redirecting
stdin
withinhandle
, andstdout
to an output stream. Get the pipe handle (p) - open the second subprocess, redirecting
stdin
with previous processstdout
, andstdout
to an output stream - let the second process
communicate
. It will "pull" the first one by consuming its output: both processes work in a pipe fashion - get return codes and print the result
Note: you get "format error" because one or both executables are actually shell or other non-native executables. In that case, just add the shell=True
option to the relevant Popen
calls.
Post a Comment for "Python Subprocess Hangs"