Kill a process running on a port

Kill a process running on a port

December 19, 20243 min read

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:

lsof -i :YOUR_TROUBLING_PORT

Example

lsof -i :5000

Output

COMMAND     PID              USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
RandomProc 53466 elizabethmanrique   33u  IPv4 0xf9e1f957a97a7c5f      0t0  TCP *:commplex-main (LISTEN)

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:

kill -9 YOUR_TROUBLING_PID

Example

kill -9 53466

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:

lsof -i :YOUR_TROUBLING_PORT -t | xargs kill -9

And we can go a step further by moving to a shell function:

function killport (){
  lsof -i :"$1" -t | xargs kill -9
  lsof -i :"$1" -t 2>/dev/null >/dev/null || printf "killed processes on port %s
" "$1"
}

The command xargs sends the result from lsof as an input to the command kill.

Use example

killport 5000

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 😂.