How to Kill the Django Development Server Without Ctrl+C
Let's say you're developing a Django project and you've lost track of the terminal window that ran your python manage.py runserver command. If you can't press Ctrl+C in the terminal, how do you stop the server?
Finding the runserver Process
First, we need to find the ID of the manage.py runserver process.
On Linux, you can list all processes with the following command:
ps aux
To search the results, you can pipe the output of that command into the grep command:
ps aux | grep manage.py
If you want to search multiple words, enclose them in single quotes ' or double quotes ":
ps aux | grep 'manage.py runserver'
This should give you rows of table data such as:
lance 12839 0.0 0.1 57068 49840 pts/25 S+ 07:11 0:00 python manage.py runserver lance 12840 23.0 0.2 435156 67752 pts/25 Sl+ 07:11 4:40 /home/lance/django-workout/.venv/bin/python manage.py runserver lance 23752 0.0 0.0 4040 1980 pts/30 S+ 07:31 0:00 grep --color=auto manage.py runserver
This can be confusing because there are a few numbers here and I'm not sure what each number represents.
To prepend a row of headers, we can run two commands back-to-back:
ps aux | head --lines=1 && ps aux | grep 'manage.py runserver'
The head command is used for printing the beginning of a file, or, if no file is specified, it reads standard input in the console.
We're looking for the PID or the "Process ID":
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND lance 12839 0.0 0.1 57068 49840 pts/25 S+ 07:11 0:00 python manage.py runserver lance 12840 23.0 0.2 435156 67752 pts/25 Sl+ 07:11 4:40 /home/lance/django-workout/.venv/bin/python manage.py runserver lance 23752 0.0 0.0 4040 1980 pts/30 S+ 07:31 0:00 grep --color=auto manage.py runserver
There are three to pick from. Which do we choose?
We can kill either of the first two, PID 12839 or PID 12840. They are related. Notice that they have the same start time.
If we read the command from the third process, we can see it's a grep command. That's the one we just ran to search for results. That process is already gone by the time we're reading the table.
Killing a Process
Now that we know the process ID, we can tell the operating system to stop it:
kill 12839
Zero results suggests the command was successful, but we can double check.
Verify the Process was Terminated
We can confirm this worked by checking our process list again:
ps aux | head --lines=1 && ps aux | grep 'manage.py runserver'
You could also load up http://127.0.0.1:8000 in your browser and see if your Django project is still being served there.
Summary
I had this happen to me when I started a server from the VSCode integrated terminal right when VSCode decided to restart.