How to kill a process by lsof port

Introduction

From this tutorial you would learn how to kill a process by lsof port info.

Environments

  • Linux/Mac OS

The Process

First we start a process that listening to a port:

➜  bswen ./start.sh
    Server address: http://127.0.0.1:4000/

➜  bswen lsof -i:4000
COMMAND   PID       USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
ruby    10524 xxx    7u  IPv4 0x60d94730b43387ef      0t0  TCP localhost:terabase (LISTEN)

we found that the server port is 4000 Next we stop the process by run this command:

➜  bswen kill -9 $(lsof -ti tcp:4000)
➜  bswen lsof -i:400
➜  bswen 

We found that the process is killed successfully.

Summary

The key command is kill -9 $(lsof -ti tcp:the_port)

You can find detail documents about the linux and lsof here: