2 years ago
#62333

bhdrozgn
How to terminate two subprocesses that one reads others output?
I have a python code that runs tshark
commands. Normally, this tshark command can be run with just one subprocess but there is an issue with my remote capture device so I need to send raw output of tshark to another tshark to process it, otherwise I can't see output until I terminate the command.
The problem here is when I try to terminate these subprocesses, they won't be terminated. I tried Ctrl+C, setting a timer for while loop, creating an keyboard input exception but it still keeps running. If I press Ctrl+C a new line comes to terminal for me to enter a new command just like the process finished but it immediately continues to print line
.
Here is my code:
import os
import signal
import subprocess
import time
import keyboard
raw_shark = subprocess.Popen(['tshark', '-i', 'rpcap://192.168.0.100:2002/radiotap1', '-l' '-w', '-'],
stdout=subprocess.PIPE)
t_shark = subprocess.Popen(['tshark', '-r' '-' '-l', '-S', '-PV', '-Tfields',
'-e', 'frame.number', '-e', 'radiotap.datarate', '-E', 'separators=\;'],
stdin = raw_shark.stdout)
pid_raw = raw_shark.pid
pid_t = t_shark.pid
start_time = time.time()
# while time.time() - start_time < 15:
while True:
# if keyboard.read_key() == 'q':
# break
line.t_shark.stdout.readline().decode()
if line != '':
print(line)
elif t_shark.poll() is None:
print('Caught up with the process')
else:
break
t_shark.terminate()
raw_shark.terminate()
try:
os.kill(pid_t, 0)
t_shark.kill()
print('Force killed t_shark')
except OSError:
print('Gracefully terminated t_shark)
try:
os.kill(pid_raw, 0)
raw_shark.kill()
print('Force killed raw_shark')
except OSError:
print('Gracefully terminated raw_shark)
After pressing Ctrl+C, I can still see these commands run by running ps aux | grep -i tshark
, both subprocesses keeps running.
If I run tshark -i rpcap://192.168.0.100:2002/radiotap1 -l -w myfifo | tshark -i myfifo -l -S -PV -Tfields -e frame.number -e radiotap.datarate -E separator=\;
in my terminal it runs fine and I can terminate it with presiing just Ctrl+C.
It doesn't even detect keypresses or checks time when in the while loop, what am I doing wrong here and how can I end these subprocesses?
EDIT: I think I understood what is happening here. When I run the code it first return an AttributeError
exception, which says that 'NoneType' object has no attribute 'readline'
. And program terminates itself but I still continue to see outputs of these subprocesses in my terminal. If I open an try-except
block in my while
loop, I can ignore this exception and continue my loop. What is the reason for this exception? Is there a better way to solve this than:
start_time = time.time()
while time.time() - start_time < 15:
try:
### some code
except AttributeError:
pass
python
linux
subprocess
popen
tshark
0 Answers
Your Answer