Scrum And Agile Methodology
March 13, 2020Unhandled Promises Sent Through To App Insights In Node JS
June 23, 2020I used to have trouble with processes blocking ports while developing. I would type up a number of commands trying to find the pid of the process that’s blocking the port and kill that process. It was rather frustrating. Eventually I took the commands and wrote a script that kills processes based on the port that it’s using.
lsof -i:$1 | awk '{print $2}' | grep -v -e "PID" | sort -u > temp.txt | |
pids=`cat temp.txt` | |
rm temp.txt | |
echo "The ids: $pids" | |
for id in $pids; do | |
echo "killing $id"; | |
kill -9 $id; | |
done |
You run it with ./kill_script_by_port.sh
with the port number as an argument.
The first line uses the lsof
command to get the processes using that port. For example lsof -i:52639
outputs the following on my machine
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME | |
Code\x20H 6181 tielman 52u IPv6 0x570f09f514ea1165 0t0 TCP *:52639 (LISTEN) |
This output gets piped into awk
which gets the 2nd word of every line. grep
removes the PID
word. Finally sort -u
removes any duplicate PIDs.
The rest of the code reads the PIDs into an array and loops through them killing all the processes that use the port.
If there’s a particular process you know you don’t want to kill, you can put the command for the process as an argument to grep -v -e
before the awk
in the pipeline. That process will be removed from the lsof
output.