title: How privilege elevation works and controlling the elevated process in Python
body: <p>Consider the following python code which is split between two files. The <code>main</code> module is trying to run the <code>dhcp</code> with elevated privileges. I am making use of <a href="https://github.com/barneygale/elevate" rel="nofollow noreferrer">elevate</a> to do the elevation.</p>
  <pre class="lang-py prettyprint-override"><code># main.py
  import subprocess, time
  
  if __name__ == '__main__':
      print(&quot;main started&quot;)
      p = subprocess.Popen(['python', 'dhcp.py'])
      time.sleep(6)
      p.terminate()
      p.wait()
  
  # dhcp.py
  from elevate import elevate
  elevate()
  print(&quot;I am an elevated process&quot;)
  </code></pre>
  <p>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 <code>subprocess</code>, then the elevation will restart <code>main</code> such that I see <code>main started</code> printed twice.</p>
  <p>My questions:</p>
  <ol>
  <li>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 <code>main started</code> is seen twice when <strong>not</strong> using subprocess. Is this understanding correct?</li>
  <li>As the code is written, the <code>dhcp</code> will not be terminated by main because <code>elevate</code> has restarted the <code>dhcp</code> process which means <code>p</code> is no longer referencing the correct process (at least, this is my understanding). Is there some way to run <code>dhcp</code> without restarting <code>main</code> process and still retain control over the <code>dhcp</code> process?</li>
  <li>I also tried multiprocessing to start the <code>dhcp</code> (target was a function in <code>dhcp</code> - not shown) but in that case I see <code>main started</code> being printed again after the elevation (i.e. <code>main</code> 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 <code>main</code> process dies.</li>
  </ol>
  <p>ETA: tests run on Windows 10 but I am looking to be able to do this on both Windows and Linux.</p>