0

I am working on a simple flask Application and I have an endpoint which creates a bash session on request. I want the process to be retained even if I kill flask.

The process is started using subprocess.Popen() and I want it to persist even after performing killall python from the terminal.

I tried setting the preexec_fn=os.setsid and preexec_fn=setpgrp argument on Popen but running killall is still killing the bash-shell that I created within my Flask application.

Relevant code:

def run_command(command):
        Process.proc = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            preexec_fn=os.setsid,
        )

run_command(['bash', '-c', 'for((i=0;i<1000;i++)); do echo $i; sleep 1; done; echo EOF'])

I'd appreciate any pointers. Thank you.

  • 1
    You may wish to refer to [this thread](https://stackoverflow.com/questions/28025402/how-to-kill-subprocesses-when-parent-exits-in-python) as by default, child processes do not exit when parent is killed, however you have `stdout` and `stderr` being piped back to parent, so when the parent process is killed, the child process, having the other end of the pipe died, also dies. If you remove the `stdout` and `stderr` arguments, you will find that the program exits immediately after calling `Popen`, while `bash` will continue to execute and echo numbers onto the terminal. – metatoaster Feb 18 '20 at 11:13

1 Answers1

0

Instead of using Popen directly you may want to use subprocess.run() which is recommended in the docs (17.5.1).

# Python3.5 or above:
from subprocess import PIPE, run

def run_command(cmd:str):
    run(cmd, universal_newlines=True)

def run_piped_command(cmd:str):
    result = run(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True)
    return result.stdout, result.stderr

If you dont pipe the output as stated by @metatoaster, process will continue executing, and if you run the killall python command it will output a nice python: no process found message.

Jon G. Labat
  • 1
  • 1
  • 3