'python "signal only works in main thread of the main interpreter" in flask with subprocess

I am current working on a flask web server, and want to use a function to finish the workflow of child processes when trigger ctrl+c from the parent process.

main.py is the parent process, starting by python3 main.py directly.

And the child processes(app.py) is started with the subprocess.popen(...) after the main.py.

# main.py
def get_flask_env():
    flask_env = os.environ.copy()
    if "FLASK_APP" not in flask_env:
        flask_env["FLASK_APP"] = "./server/app.py"
    if "FLASK_ENV" not in flask_env:
        flask_env["FLASK_ENV"] = "development"
    return flask_env

def start_flask():
    flask_env = get_flask_env()
    command = []
    # the command to start app.py, would be: flask run --host 0.0.0.
    command.append(python_command)
    command.append("-m")
    command.append("flask")
    command.append("run")
    command.append("--host")
    command.append("0.0.0.0")
    monitor = subprocess.Popen(command, env=flask_env)

when I start the flask server(app.py), I catch the error in the flask server to handle clear:

def handle_exit(*args):
    # clear multiprocessing here
    pass

then set the signal in app.py:

signal.signal(signal.SIGTERM,  handle_exit)
signal.signal(signal.SIGINT,  handle_exit)

I had success use this in the parent process(main.py), but had problem if I use signal in child processes, the problem:

signal only works in main thread of the main interpreter

So how to use the signal properly subprocess?

Edited:

For now, I use the subprocess.run(...) in the main.py to kill all the multiprocessing with linux command: pkill, but this is not a cross-platform way and might terminate the process without properly wait it finish.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source