Skip to content

Find and kill processes on Linux and Mac by port number

kill processes on Linux shell logo

This tutorial will quickly show you how to to find and kill processes on Linux, Mac and other Unix based systems such as CentOS based on the port number.

Finding a process on Unix

Let’s say I would like to kill a database process such as Postgres, which in turn, usually runs on the standard port 5432. First, let’s list the processes attached to port 5432:

lsof -i :5432

Which prints a list of processes connected to port 5432:

COMMAND     PID        USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
pgAdmin4  31159 bgasparotto   21u  IPv6 0xabf485c509f250b7      0t0  TCP localhost:61843->localhost:postgresql (CLOSE_WAIT)
pgAdmin4  31159 bgasparotto   22u  IPv6 0xabf485c4f2d26737      0t0  TCP localhost:62091->localhost:postgresql (CLOSE_WAIT)
java      42403 bgasparotto  126u  IPv6 0xabf485c50bdb0737      0t0  TCP localhost:57785->localhost:postgresql (ESTABLISHED)
java      42403 bgasparotto  134u  IPv6 0xabf485c50bdb12b7      0t0  TCP localhost:57786->localhost:postgresql (ESTABLISHED)

Often you will find that it prints more processes than you were expecting. However, in our example, I know that pgAdmin4 is a strong candidate to be running our Postgres since it is the admin application, hence, let’s copy its process id (PID) 31159.

Killing a process on Unix

With the PID in hands, let’s kill it:

kill 31159

If you get an error saying you don’t have permission to kill this process as it might not have been started by your user, try adding sudo before the command (assuming you have admin privileges).

Now, if you list the processes connected to port 5432 again, you will notice that pgAdmin4 is no longer there:

lsof -i :5432

COMMAND     PID        USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
java      42403 bgasparotto  126u  IPv6 0xabf485c50bdb0737      0t0  TCP localhost:57785->localhost:postgresql (ESTABLISHED)
java      42403 bgasparotto  134u  IPv6 0xabf485c50bdb12b7      0t0  TCP localhost:57786->localhost:postgresql (ESTABLISHED)

Hope this helped you to kill processes on Linux and Mac.
Cya!

References

Leave a Reply

Your email address will not be published. Required fields are marked *