How to kill a process by port on MacOS, a la fuser -k 9000/tcp

87,148

Solution 1

lsof -P | grep ':PortNumber' | awk '{print $2}' | xargs kill -9

Change PortNumber to the actual port you want to search for.

Solution 2

Adding the -t and -i flags to lsof should speed it up even more by removing the need for grep and awk.

lsof -nti:NumberOfPort | xargs kill -9

lsof arguments:

  • -n Avoids host names lookup (may result in faster performance)
  • -t Terse output; returns process IDs only to facilitate piping the output to kill
  • -i Selects only those files whose Internet address matches

kill arguments:

  • -9 Non-catchable, non-ignorable kill

Solution 3

You can see if a port if open by this command

 sudo lsof -i :8000

where 8000 is the port number

If the port is open, it should return a string containing the Process ID (PID).

Copy this PID and

kill -9 PID

If you need to see all the open ports, you can perform a Port Scan in the Network Utility application.

Solution 4

Add -n to lsof and you remove the reverse DNS lookup from the command and reduce the run time from minutes to seconds.

lsof -Pn | grep ':NumberOfPort' | awk '{print $2}' | xargs kill -9

Solution 5

  1. Check your port is open or not by

sudo lsof -i : {PORT_NUMBER}

COMMAND PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
java    582 Thirumal  300u  IPv6 0xf91b63da8f10f8b7      0t0  TCP *:distinct (LISTEN)

2. Close the port by killing process PID

sudo kill -9 582
Share:
87,148
Kris
Author by

Kris

Cynefin, Complexity, Agile, Business, Architecture, Teams

Updated on September 18, 2022

Comments

  • Kris
    Kris over 1 year

    On linux I can kill a process knowing only the port it is listening on using fuser -k 9000/tcp, how do I so the same on MacOS?

  • Kris
    Kris almost 12 years
    I just had to add -9 to the end to get this to work, but I believe that is due to the nature of the listening application and not generally recommended practice, to kill -9 that is.
  • aces.
    aces. over 11 years
    @Kris - lsof -P | grep ':NumberOfPort' | awk '{print $2}' | xargs kill -9 worked!
  • yass
    yass almost 7 years
    You are repeating other answer
  • Ben Sh
    Ben Sh almost 7 years
    Works and is more concise than the accepted answer!
  • daleyjem
    daleyjem over 4 years
    WAY faster with this approach