title: Stop a background process in flask without creating zombie processes
body: <p>I need to start a long-running background process with subprocess when someone visits a particular view.</p>
  
  <p><strong>My code</strong>:</p>
  
  <pre><code>from flask import Flask
  import subprocess
  
  app = Flask(__name__)
  
  @app.route("/")
  def index():
      subprocess.Popen(["sleep", "10"])
      return "hi\n"
  
  if __name__ == "__main__":
      app.run(debug=True)
  </code></pre>
  
  <p>This works great, for the most part. </p>
  
  <p>The problem is that when the process (sleep) ends, <code>ps -Af | grep sleep</code> shows it as <code>[sleep] &lt;defunct&gt;</code>. </p>
  
  <p>From what I've read, this is because I still have a reference to the process in <code>flask</code>.</p>
  
  <p>Is there a way to drop this reference after the process exits?</p>
  
  <p>I tried doing <code>g.subprocess = subprocess.Popen(["sleep", "10"])</code>, and waiting for the process to end in <code>@app.after_request(response)</code> so I can use <code>del</code> on it, but this prevents flask from returning the response until the subprocess exits - I need it to return the response before the subprocess exits.</p>
  
  <p><strong>Note</strong>: </p>
  
  <p>I need the subprocess.Popen operation to be non-blocking - this is important.</p>