0
votes

Consider the following python code which is split between two files. The main module is trying to run the dhcp with elevated privileges. I am making use of elevate to do the elevation.

# main.py
import subprocess, time

if __name__ == '__main__':
    print("main started")
    p = subprocess.Popen(['python', 'dhcp.py'])
    time.sleep(6)
    p.terminate()
    p.wait()

# dhcp.py
from elevate import elevate
elevate()
print("I am an elevated process")

My aim is to run the dhcp file (a dhcp server) without restarting my main process AND have some control over the dhcp server (terminate it at some point; ideally, gracefully). If I do not use subprocess, then the elevation will restart main such that I see main started printed twice.

My questions:

  1. I understand that elevation in both Windows and Linux has to be at the process level (i.e. you cannot just invoke a single function with elevated privileges) - hence why main started is seen twice when not using subprocess. Is this understanding correct?
  2. As the code is written, the dhcp will not be terminated by main because elevate has restarted the dhcp process which means p is no longer referencing the correct process (at least, this is my understanding). Is there some way to run dhcp without restarting main process and still retain control over the dhcp process?
  3. I also tried multiprocessing to start the dhcp (target was a function in dhcp - not shown) but in that case I see main started being printed again after the elevation (i.e. main is restarted) which was a surprise as I thought it would be a separate child process. Why would this not be separate? And, my experiments show that this also suffers from the same issue as #2 - i.e. cannot terminate the child process. It seems to only stop when the main process dies.

ETA: tests run on Windows 10 but I am looking to be able to do this on both Windows and Linux.