From e41338084eee8fb158375ca391113956b0a1f5d9 Mon Sep 17 00:00:00 2001 From: Alejandro Dustet Date: Fri, 14 Jan 2022 09:36:09 -0500 Subject: [PATCH] Add helper to list process running in a given port Why: ---- Whenever we run a command to use a certain port and we get an error that the port is in use, we have can either: 1. Clear the port so our new process can use it 2. Try and use a new port for the command we just typed In order to make a decision about it, we need information on what is running on that port, so we can determine if we want to stop that process or if it's important enough to keep. What: ---- Two new commands are added to /bin. One to output information about the process using a provided port: ``` bash $ whats-in-port 3000 $ COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME $ ruby 25583 root 11u IPv4 0xee20607697a79bf7 0t0 TCP *:irdmi (LISTEN) ``` This command uses the [lsof] program to get information of the process utilising that port. And another one making use of the previous utility to kill the process running in that port: ``` bash $ clear-port 3000 ``` [lsof]: https://linux.die.net/man/8/lsof Co-authored-by: Mike Burns Co-authored-by: Edward Loveall --- bin/clear-port | 15 +++++++++++++++ bin/whats-in-port | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100755 bin/clear-port create mode 100755 bin/whats-in-port diff --git a/bin/clear-port b/bin/clear-port new file mode 100755 index 0000000..837079a --- /dev/null +++ b/bin/clear-port @@ -0,0 +1,15 @@ +#!/bin/sh + +# Kills the process running on the provided port +# +# clear-port 3000 + +if [ -n "$1" ]; then + port_num="$(lsof -ti4TCP:"$1")" + if [ $? -eq 0 ]; then + kill "$port_num" + fi +else + echo >&2 Usage: clear_port port-number + exit 1 +fi diff --git a/bin/whats-in-port b/bin/whats-in-port new file mode 100755 index 0000000..476f77f --- /dev/null +++ b/bin/whats-in-port @@ -0,0 +1,16 @@ +#!/bin/sh + +# List process running on provided port +# +# whats-in-port 3000 +# +# output: +# COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME +# ruby 25583 root 11u IPv4 0xee20607697a79bf7 0t0 TCP *:irdmi (LISTEN) + +if [ -n "$1" ]; then + lsof -ni4TCP:"$1" +else + echo >&2 Usage: whats_in_port port-number + exit 1 +fi