shellkilllsof

kill a process on a specific port by name


I have a process running on port 3200, which communicates with other processes on other ports.

I know I can kill a process on a given port by doing kill -9 $(lsof -t -i:3200).

My problem is that the output of lsof also contains the other processes that are communicating with the one I want to kill:

COMMAND         PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
java          16379 tirafesi  102u  IPv6 156964      0t0  TCP localhost:41162->localhost:3200 (ESTABLISHED)
python3       16793 tirafesi    3u  IPv4 158199      0t0  TCP localhost:51101->localhost:3200 (ESTABLISHED)
processtokill 16802 tirafesi    8u  IPv4 156963      0t0  TCP *:3200 (LISTEN)
processtokill 16802 tirafesi   10u  IPv4 158788      0t0  TCP localhost:3200->localhost:51101 (ESTABLISHED)
processtokill 16802 tirafesi   11u  IPv4 156965      0t0  TCP localhost:3200->localhost:41162 (ESTABLISHED)

How can I kill the process that is on port 3200 and is named processtokill?


Solution

  • You want to kill the process that is LISTENing on port 3200, so:

    kill -9 $(lsof -t -i:3200 -sTCP:LISTEN)