Clt+C
can be used to stop the Flask app, running on the development server. I would like also to stop the subprocesses that run with the app. With the stop_processes
and @app.teardown_appcontext
, I have tried to signal the closing of the app and trigger the termination of the subprocesses.
When I press Ctrl+C
, the Flask development server stops, however the subprocesses are put to sleep rather than getting termined. Actually, it is the same result as not using the stop_processes
function at all.
import flask
import subprocess
import signal
import os
def function1():
# Create a new subprocess to run 'script1.py', setting it in its own process group
p = subprocess.Popen(['python', 'script1.py'], preexec_fn=os.setsid)
p.wait()
return p
def function2():
# Create a new subprocess to run 'script2.py', setting it in its own process group
p = subprocess.Popen(['python', 'script2.py'], preexec_fn=os.setsid)
p.wait()
return p
app = Flask(__name__)
subprocesses = []
@app.route('/process')
def process():
global subprocesses
proc1 = function1()
subprocesses.append(proc1)
proc2 = function2()
subprocesses.append(proc2)
return "Processing completed!"
@app.teardown_appcontext
def stop_subprocesses(exception=None):
print('Stopping subprocesses ... ')
global subprocesses
for p in subprocesses:
try:
# Attempt to kill the entire process group associated with each subprocess
os.killpg(os.getpgid(p.pid), signal.SIGKILL)
except Exception as e:
print(f"Failed to kill subprocess {p.pid}: {e}")
5