I have 3 functions to perform:
- Launch
tcpdump
- Perform network activity so that
tcpdump
can generate a pcap for it - Kill
tcpdump
after network activity in step 2 is complete.
Launch
def launch_tcpdump(output_filename):
import subprocess as sp
import time
process = sp.Popen(['tcpdump', '-i', 'wlo1', '-w', output_filename])
print(f"PID: {process.pid}")
time.sleep(5)
return process
if I do not sleep for 5 seconds, then before tcpdump
gets initialized, my script completes the network activity. On the other hand, sleeping for 5 seconds seems excessive and is slowing down my overall process (I have to do this multiple times and generate pcaps for each network activity).
- Are there ways for a child process to communicate to the parent process that it has initialized?
- If not, can the parent process (python) check something to determine if the process has initialized?
Note: I understand that initialized can mean different things in the case of different processes. I am guessing that once it outputs: tcpdump: listening on wlo1, link-type EN10MB (Ethernet), capture size 262144 bytes
, it's done initializing. So, reading stdout is also a potential option, but I am unable to find solutions that can read from stdout while detaching python from the child process.
You can monitor the output of
tcpdump
and return after however many lines.Notice I added the
-l
option sotcpdump
writes tostdout
as well as to the output file. You could also change this to check for the presence of the initialize line you mention in thestdout
.