Strategies for waiting for an external process to initialize

94 Views Asked by At

I have 3 functions to perform:

  1. Launch tcpdump
  2. Perform network activity so that tcpdump can generate a pcap for it
  3. 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).

  1. Are there ways for a child process to communicate to the parent process that it has initialized?
  2. 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.

1

There are 1 best solutions below

0
On

You can monitor the output of tcpdump and return after however many lines.

import subprocess as sp
import time

def launch_tcpdump(output_filename):
    lines_to_read = 200
    process = sp.Popen(['tcpdump', '-l', '-i', 'wlo1', '-w', output_filename])
    print(f"PID: {process.pid}")
    while lines_to_read > 0:
        for _ in iter(process.stdout.readline, ''):
            lines_to_read -= 1
    return process

Notice I added the -l option so tcpdump writes to stdout as well as to the output file. You could also change this to check for the presence of the initialize line you mention in the stdout.