Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to kill uvicorn cleanly?

Is there a way to kill uvicorn cleanly?

I.e., I can type ^C at it, if it is running in the foreground on a terminal. This causes the uvivorn process to die and all of the worker processes to be cleaned up. (I.e., they go away.)

On the other hand, if uvicorn is running in the background without a terminal, then I can't figure out a way to kill it cleanly. It seems to ignore SIGTERM, SIGINT, and SIGHUP. I can kill it with SIGKILL (i.e. -9), but then the worker processes remain alive, and I have to track all the worker processes down and kill them too. This is not ideal.

I am using uvicorn with CPython 3.7.4, uvivorn version 0.11.2, and FastAPI 0.46.0 on Red Hat Enterprise Linux Server 7.3 (Maipo).

like image 423
Douglas Avatar asked Feb 27 '20 00:02

Douglas


1 Answers

That's because you're running uvicorn as your only server. uvicorn is not a process manager and, as so, it does not manage its workers life cycle. That's why they recommend running uvicorn using gunicorn+UvicornWorker for production.

That said, you can kill the spawned workers and trigger it's shutdown using the script below:

$ kill $(pgrep -P $uvicorn_pid)

The reason why this works but not the kill on the parent pid is because when you ^C something, the signal is transmitted throughout all of its spawned processes that are attached to the stdin.

like image 114
Gustavo Kawamoto Avatar answered Nov 05 '22 11:11

Gustavo Kawamoto