When developing a service-oriented architecture, we may run into a situation where we want to kill the process that is listening on a given port.

Sometimes, you can accomplish this with the wonderful pkill utility, for instance if there is only one process with that name.  Otherwise, you will have to figure out which pid represents the running service and then use that to kill the service.

It can be annoying to remember where the pidfiles are stored for each service, and sometimes you just want to use a sledghammer to whack the process.

We can easily list the processes listening on a given port with:

sudo lsof -n -P -i :22

(using sudo because lsof may only have visibility to processes owned by the current user, depending on its compile settings.)

So now, the trick is to turn the output, which looks like this:

~/bin/ #>lsof -n -P -i :1337
COMMAND     PID           USER   FD   TYPE     DEVICE SIZE/OFF NODE NAME
redis-ser 86099 aaronblohowiak    4u  IPv4 0x0e83c748      0t0  TCP *:1337 (LISTEN)

into something that we can easily kill -9. (sledgehammer!)

To do that, I just created a little bash script in my path named 'killport' and made sure to chmod +x it.

#!/usr/bin/env bash

kill -9 `lsof -n -P -i :$1 | (read; awk '{print $2}')`

To use it, you just sudo killport 1337 and it will whack whatever is listening on that port.

what is the read; awk stuff?

the (read; awk ...) will discard the first line of the lsof output and then awk will select the second field. Note that since the $2 is within single quotes, it will NOT get substituted with the second argument to our script. However, since $1 isn't in single quotes, it WILL be substituted, which is how we "pass in" the port number to lsof from the command line.