I am trying to redirect a subprocess
stdout
to two different processes.
Doing it to one works fine, but not quite working with two different processes
Code:
def terminate_processes(*args):
try:
for i in reversed(args):
try:
i.terminate()
except:
pass
except:
pass
def main(x='192.168.0.2'):
# system('sudo nmap -O '+x+'|grep "Running: " > os_detect.txt')
# system('cat os_detect.txt|cut -d " " -f2 > os.txt')
# system('cat os_detect.txt|cut -d " " -f3 > os_version.txt')
p1 = subprocess.Popen(['sudo', 'nmap', '-O', str(x)], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', 'Running: '], stdin=p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(['cut', '-d', ' ', '-f2'], stdin=p2.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
p4 = subprocess.Popen(['cut', '-d', ' ', '-f3'], stdin=p2.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
while p3.poll() is None:
for line in p3.stdout.readlines():
if line.strip():
print(line.strip())
while p4.poll() is None:
for line in p4.stdout.readlines():
if line.strip():
print(line.strip())
terminate_processes(p1,p2,p3,p4)
As i said should work in theory cause works when only using p3
and not p4
,
but not working in this case maybe because the stdout
is locked.
Any guidance would be really appreciated.
And i am reversing the args
array inside terminate function cause killing the child process before killing the parent one.