Basically, I have the following code segment
#!/usr/bin/env python3
import os
import sys
import subprocess
import time
import shlex
import paho.mqtt.client as paho
if __name__ == "__main__":
r, w = os.pipe()
processId = os.fork()
if processId:
# wait to ensure tshark is started appropriately
os.close(w)
r = os.fdopen(r,'r')
while True:
str = r.read()
print("{} {}".format("Message from child: ",str))
if str == "ok":
break
print("Parent exit")
else:
os.close(r)
w = os.fdopen(w,'w')
cmd = "tshark | grep EAP"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, shell=True, universal_newlines=True)
w.write("ok")
# send signal to parent stating tshark has started appropriately
for output in iter(process.stdout.readline, ""):
pass #if contains EAP packet, do something
I am trying to create a child process that capture packets through tshark
, instantly based on the packet captured to perform some action. I attempted to fork a process so that for the parent process, some action can be done and the child process can capture the packets. I also would like to first ensure child has successfully started tshark
before the parent process continue the job.
Here comes my questions...
1) Is the subprocess.Popen
's pipe interfering with the pipe created from os.pipe()
?
I was thinking that both were not interfering with each other since they are two distincting sets of pipe. However, I noticed that the parent process cannot receive the message through the read pipe and only if subprocess
has some output, the parent will then receive the message. I I need some help here...
2) Is there any approach that the output from subprocess
can be capture on a line basis? I have read this suggested that it is possible to capture output while subprocess
is still running, however it only returns the output once the buffer size is reached.
3) Is it a good or bad approach for mixing os.pipe()
, os.fork()
and subprocess.Popen
all at once? I am just not sure whether someone will be doing this or there is any better alternatives? Your help will be highly appreciated :)