How To Kill Processes On MacOS
3 min readI’m sure at some point you have gotten the dreaded error message:
Port #### is already in use.
The problem here is that when we open a port on any machine we start a process and if that port was not closed properly (i.e. the process ended properly) we end up with a rouge process running in the background.
Before I finally took the time to dig into this I just did the following:
This article will show you a better way to go about handling rouge processes on macOS.
TLDR
Using lsof, xargs, & kill to stop processes
lsof
is a command that will give us a list of open files. When I first read that I was a little confused because I was thinking in terms of like an open Pages document which is true, but you must think of a process as an open file too. As an example running the command on my Mac right now returns an entry from Spotify while I am listening to the Joe Rogan Experience:
Let’s see what -t
will do:
So with -t
we can get a list of all the processes running on our machine. Let’s see what exactly i
is doing in in that chain of flags.
Now if we pair -ti
together we can get only a list of pids that correlate to processes that are running on the network.
With the error message we get back we know what port is still open so following the documentation surrounding -i
we can provide that as an argument to our query.
xargs
constructs an argument or list of arguments to pipe into a command so we can turn around and send the pid or pids to the kill
command.
Let’s make the command reusable.
I wanted to create a reusable function that wrapped the above command so I came up with the following and assigned it to an alias.
Now I have a simple one liner to reach for when I get that damn error message.
Related Articles
A Far Too In-Depth Guide To SSH For Web Developers
Everything I have learned when it comes to SSH after setting up my Raspberry Pi Cluster.
Python Scripting In iTerm2
How to use the Python Scripting API in iTerm2 to open several tabs and execute commands in those tabs.
Migrating From Yarn To Pnpm
My experience moving from classic yarn to pnpm as my package manager in JavaScript land.
Getting Started With Python3
Installation and setup of Python3 on macOS & development with Visual Studio Code.
Deploying With Now
How to deploy with Zeit's Now platform.
Cody is a Christian, USN Veteran, Jayhawk, and an American expat living outside of Bogotá, Colombia. He is currently looking for new opportunities in the tech industry.