title: Starting a daemon process from within Python script and killing it via os.kill later
body: <p>In Linux environment, I'm trying to use python to start a daemon process if it's not already started, get the PID, and then at some point later kill that process using os.kill(pid, signel.SIGTERM). This results in the daemon process becoming defunct, if it was started from my script.</p>
  
  <p>Here's the example code:</p>
  
  <pre><code>#!/usr/bin/env python3
  
  import os, subprocess, time, signal, getpass
  
  p = subprocess.Popen(['sleep', '30'])
  
  os.kill(int(p.pid), signal.SIGTERM)
  
  os.system('ps -fu ' + getpass.getuser())
  </code></pre>
  
  <p>I get the following as output:</p>
  
  <pre><code>UID        PID  PPID  C STIME TTY          TIME CMD
  pchernik  7179 10629  0 16:07 pts/0    00:00:00 python3 ./boom
  pchernik  7180  7179  0 16:07 ?        00:00:00 [sleep] &lt;defunct&gt;
  </code></pre>
  
  <p>My end goal is:</p>
  
  <ul>
  <li>Using a .pid file check whether daemon is running</li>
  <li>Start daemon if not running, get PID and save it to .pid file</li>
  <li>Do some other stuff (socket communication with daemon)</li>
  <li>Stop daemon and start it again using os.kill(pid, signal.SIGTERM)</li>
  </ul>
  
  <p>Can't use p.kill() b/c I might not have "p" to work with, if process is already started outside of this python script.</p>
  
  <p>Can't use wait() as I have more than 1 process started this way.</p>
  
  <p>I tried adding preexec_fn=os.setsid to Popen - doesn't seem to help</p>
  
  <p>How can I start a daemon process from within Python script and completely detach it from my Python process?</p>
  
  <p>Thanks,
  -Pavel</p>