Kill a process running on a port
Okay, I'm writing this article because, as simple as this may sound, every now and then a running process occupying a particular port prevents my computer from running another and I end up wasting 5 mins searching for the answer to the same question:
How do I kill a process running on a specific port 😑?
The answer will vary based on the OS you work on, but in my case, I'll focus on macOS.
Identify the process
Starting from El Capitan we can use the UNIX command lsof
to know which open files and the process related are running. This command stands for list open files, and if you use it along with the argument -i
you can know which network port is associated with a process. The full command is:
Example
Output
After running this command in the terminal, you will know which PID (process identifier) is linked, which will help to actually kill the process 🗡.
In the example, the PID is 53466.
Kill the process
We can use the command kill
, which surprisingly doesn't kill the process; instead, it sends a signal to the process requesting to do something (the app will respond accordingly).
If we want the command kill
to actually exit a process, then we should use it along with the argument -9
(use kill -l
to see all the options available). The full command is:
Example
If all is good with the PID, then your process will be exited. You can run the command lsof
again to make sure it is not running.
Bonus
We can make this even shorter with a one-line command:
And we can go a step further by moving to a shell function:
The command
xargs
sends the result fromlsof
as an input to the commandkill
.
Use example
And that's it!
You can kill a process with two simple commands or shorten it to just one. It's up to you!
Thanks for reading! Writing this article helped me to understand more about some commands and finally have a place to directly find the answer to my ever-lasting question 😂.