DEV Community

Andreas Bergström
Andreas Bergström

Posted on • Edited on

Kill a process using a specific port (MacOS)

Simply do:
`lsof -ti :[port number] | xargs kill

This command is a combination of two commands, lsof and xargs, that are used together to find and kill a process that is using a specific port. Let's break down each part of the command:

  • lsof: This is short for "list open files," and it is a Unix/Linux command used to display information about open files and the processes that opened them. In this context, it is used to find processes that have open network connections.
  • -ti: These are options passed to the lsof command.
    • -t: This option tells lsof to display only the process IDs (PIDs) of the processes that match the specified criteria.
    • -i: This option is followed by a specification of the network connection to be matched. In this case, it is :[port number], where [port number] should be replaced with the actual port number you want to check.
  • :[port number]: Replace [port number] with the actual port number you want to check for open connections.
  • |: This is the pipe symbol, which is used to pass the output of one command (in this case, lsof) as input to another command (in this case, xargs).
  • xargs: This command reads items from standard input, separated by whitespace or newlines, and executes a specified command with those items as arguments. In this case, it is used to execute the kill command with the PIDs obtained from lsof.
  • kill: This is a Unix/Linux command used to send signals to processes, typically to terminate them. In this case, it is used to terminate the process that has an open connection on the specified port.

When you run lsof -ti :[port number] | xargs kill, the command will find the process that has an open connection on the specified port, and then kill that process using the kill command.

Further Tips on Similar Commands

  1. lsof -i: To list all processes with open network connections, use the lsof -i command.
  2. kill -9 [PID]: If the process doesn't terminate with the regular kill command, you can use kill -9 [PID] to send a stronger signal (SIGKILL) to the process.
  3. netstat -tuln: To view a list of all listening ports along with the associated programs, use the netstat -tuln command.
  4. pgrep [process name]: To find the PID of a process based on its name, use the pgrep command, followed by the process name.
  5. pkill [process name]: To kill a process based on its name, use the pkill command, followed by the process name. `

Top comments (0)